blob: be6f279466f85e6c4e281b6f2fc5fde9fe896c69 [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. Hudsonade8c8b22002-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. Hudsonade8c8b22002-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. Hudsonade8c8b22002-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. Hudsonade8c8b22002-11-27 16:29:26 +000094 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000095 return mod;
96 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000097 else {
98 s = strrchr(type->tp_name, '.');
99 if (s != NULL)
100 return PyString_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000101 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Michael W. Hudsonade8c8b22002-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);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000217 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000218 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
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000365type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000367 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000368 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000369
370 mod = type_module(type, NULL);
371 if (mod == NULL)
372 PyErr_Clear();
373 else if (!PyString_Check(mod)) {
374 Py_DECREF(mod);
375 mod = NULL;
376 }
377 name = type_name(type, NULL);
378 if (name == NULL)
379 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000380
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000381 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
382 kind = "class";
383 else
384 kind = "type";
385
Barry Warsaw7ce36942001-08-24 18:34:26 +0000386 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000387 rtn = PyString_FromFormat("<%s '%s.%s'>",
388 kind,
Barry Warsaw7ce36942001-08-24 18:34:26 +0000389 PyString_AS_STRING(mod),
390 PyString_AS_STRING(name));
391 }
Guido van Rossumc3542212001-08-16 09:18:56 +0000392 else
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000393 rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000394
Guido van Rossumc3542212001-08-16 09:18:56 +0000395 Py_XDECREF(mod);
396 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Tim Peters6d6c1a32001-08-02 04:15:00 +0000400static PyObject *
401type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
402{
403 PyObject *obj;
404
405 if (type->tp_new == NULL) {
406 PyErr_Format(PyExc_TypeError,
407 "cannot create '%.100s' instances",
408 type->tp_name);
409 return NULL;
410 }
411
Tim Peters3f996e72001-09-13 19:18:27 +0000412 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000413 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000414 /* Ugly exception: when the call was type(something),
415 don't call tp_init on the result. */
416 if (type == &PyType_Type &&
417 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
418 (kwds == NULL ||
419 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
420 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000421 /* If the returned object is not an instance of type,
422 it won't be initialized. */
423 if (!PyType_IsSubtype(obj->ob_type, type))
424 return obj;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000425 type = obj->ob_type;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000426 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000427 type->tp_init(obj, args, kwds) < 0) {
428 Py_DECREF(obj);
429 obj = NULL;
430 }
431 }
432 return obj;
433}
434
435PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000437{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000439 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
440 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000441
442 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000443 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000444 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000446
Neil Schemenauerc806c882001-08-29 23:54:54 +0000447 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000448 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000451
Tim Peters6d6c1a32001-08-02 04:15:00 +0000452 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
453 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_itemsize == 0)
456 PyObject_INIT(obj, type);
457 else
458 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000459
Tim Peters6d6c1a32001-08-02 04:15:00 +0000460 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000461 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000462 return obj;
463}
464
465PyObject *
466PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
467{
468 return type->tp_alloc(type, 0);
469}
470
Guido van Rossum9475a232001-10-05 20:51:39 +0000471/* Helpers for subtyping */
472
473static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000474traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
475{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000476 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477 PyMemberDef *mp;
478
479 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000480 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000481 for (i = 0; i < n; i++, mp++) {
482 if (mp->type == T_OBJECT_EX) {
483 char *addr = (char *)self + mp->offset;
484 PyObject *obj = *(PyObject **)addr;
485 if (obj != NULL) {
486 int err = visit(obj, arg);
487 if (err)
488 return err;
489 }
490 }
491 }
492 return 0;
493}
494
495static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000496subtype_traverse(PyObject *self, visitproc visit, void *arg)
497{
498 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000499 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000500
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000501 /* Find the nearest base with a different tp_traverse,
502 and traverse slots while we're at it */
Guido van Rossum9475a232001-10-05 20:51:39 +0000503 type = self->ob_type;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 base = type;
505 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
506 if (base->ob_size) {
507 int err = traverse_slots(base, self, visit, arg);
508 if (err)
509 return err;
510 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000511 base = base->tp_base;
512 assert(base);
513 }
514
515 if (type->tp_dictoffset != base->tp_dictoffset) {
516 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517 if (dictptr && *dictptr)
518 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000519 }
520
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000521 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000522 /* For a heaptype, the instances count as references
523 to the type. Traverse the type so the collector
524 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000525 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000526
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000527 if (basetraverse)
528 return basetraverse(self, visit, arg);
529 return 0;
530}
531
532static void
533clear_slots(PyTypeObject *type, PyObject *self)
534{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000535 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000536 PyMemberDef *mp;
537
538 n = type->ob_size;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000539 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000540 for (i = 0; i < n; i++, mp++) {
541 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
542 char *addr = (char *)self + mp->offset;
543 PyObject *obj = *(PyObject **)addr;
544 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000545 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000546 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000547 }
548 }
549 }
550}
551
552static int
553subtype_clear(PyObject *self)
554{
555 PyTypeObject *type, *base;
556 inquiry baseclear;
557
558 /* Find the nearest base with a different tp_clear
559 and clear slots while we're at it */
560 type = self->ob_type;
561 base = type;
562 while ((baseclear = base->tp_clear) == subtype_clear) {
563 if (base->ob_size)
564 clear_slots(base, self);
565 base = base->tp_base;
566 assert(base);
567 }
568
Guido van Rossuma3862092002-06-10 15:24:42 +0000569 /* There's no need to clear the instance dict (if any);
570 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000571
572 if (baseclear)
573 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000574 return 0;
575}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000576
577static void
578subtype_dealloc(PyObject *self)
579{
Guido van Rossum14227b42001-12-06 02:35:58 +0000580 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000581 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000582
Guido van Rossum22b13872002-08-06 21:41:44 +0000583 /* Extract the type; we expect it to be a heap type */
584 type = self->ob_type;
585 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000586
Guido van Rossum22b13872002-08-06 21:41:44 +0000587 /* Test whether the type has GC exactly once */
588
589 if (!PyType_IS_GC(type)) {
590 /* It's really rare to find a dynamic type that doesn't have
591 GC; it can only happen when deriving from 'object' and not
592 adding any slots or instance variables. This allows
593 certain simplifications: there's no need to call
594 clear_slots(), or DECREF the dict, or clear weakrefs. */
595
596 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000597 if (type->tp_del) {
598 type->tp_del(self);
599 if (self->ob_refcnt > 0)
600 return;
601 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000602
603 /* Find the nearest base with a different tp_dealloc */
604 base = type;
605 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
606 assert(base->ob_size == 0);
607 base = base->tp_base;
608 assert(base);
609 }
610
611 /* Call the base tp_dealloc() */
612 assert(basedealloc);
613 basedealloc(self);
614
615 /* Can't reference self beyond this point */
616 Py_DECREF(type);
617
618 /* Done */
619 return;
620 }
621
622 /* We get here only if the type has GC */
623
624 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000625 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000626 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000627 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000628 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000629 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000630 /* DO NOT restore GC tracking at this point. weakref callbacks
631 * (if any, and whether directly here or indirectly in something we
632 * call) may trigger GC, and if self is tracked at that point, it
633 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000634 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000635
Guido van Rossum59195fd2003-06-13 20:54:40 +0000636 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000637 base = type;
638 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000639 base = base->tp_base;
640 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000641 }
642
Guido van Rossum1987c662003-05-29 14:29:23 +0000643 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000644 the finalizer (__del__), clearing slots, or clearing the instance
645 dict. */
646
Guido van Rossum1987c662003-05-29 14:29:23 +0000647 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
648 PyObject_ClearWeakRefs(self);
649
650 /* Maybe call finalizer; exit early if resurrected */
651 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000652 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000653 type->tp_del(self);
654 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000655 goto endlabel; /* resurrected */
656 else
657 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000658 /* New weakrefs could be created during the finalizer call.
659 If this occurs, clear them out without calling their
660 finalizers since they might rely on part of the object
661 being finalized that has already been destroyed. */
662 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
663 /* Modeled after GET_WEAKREFS_LISTPTR() */
664 PyWeakReference **list = (PyWeakReference **) \
665 PyObject_GET_WEAKREFS_LISTPTR(self);
666 while (*list)
667 _PyWeakref_ClearRef(*list);
668 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000669 }
670
Guido van Rossum59195fd2003-06-13 20:54:40 +0000671 /* Clear slots up to the nearest base with a different tp_dealloc */
672 base = type;
673 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
674 if (base->ob_size)
675 clear_slots(base, self);
676 base = base->tp_base;
677 assert(base);
678 }
679
Tim Peters6d6c1a32001-08-02 04:15:00 +0000680 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000681 if (type->tp_dictoffset && !base->tp_dictoffset) {
682 PyObject **dictptr = _PyObject_GetDictPtr(self);
683 if (dictptr != NULL) {
684 PyObject *dict = *dictptr;
685 if (dict != NULL) {
686 Py_DECREF(dict);
687 *dictptr = NULL;
688 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000689 }
690 }
691
Tim Peters0bd743c2003-11-13 22:50:00 +0000692 /* Call the base tp_dealloc(); first retrack self if
693 * basedealloc knows about gc.
694 */
695 if (PyType_IS_GC(base))
696 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000697 assert(basedealloc);
698 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000699
700 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000701 Py_DECREF(type);
702
Guido van Rossum0906e072002-08-07 20:42:09 +0000703 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000704 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000705 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000706 --_PyTrash_delete_nesting;
707
708 /* Explanation of the weirdness around the trashcan macros:
709
710 Q. What do the trashcan macros do?
711
712 A. Read the comment titled "Trashcan mechanism" in object.h.
713 For one, this explains why there must be a call to GC-untrack
714 before the trashcan begin macro. Without understanding the
715 trashcan code, the answers to the following questions don't make
716 sense.
717
718 Q. Why do we GC-untrack before the trashcan and then immediately
719 GC-track again afterward?
720
721 A. In the case that the base class is GC-aware, the base class
722 probably GC-untracks the object. If it does that using the
723 UNTRACK macro, this will crash when the object is already
724 untracked. Because we don't know what the base class does, the
725 only safe thing is to make sure the object is tracked when we
726 call the base class dealloc. But... The trashcan begin macro
727 requires that the object is *untracked* before it is called. So
728 the dance becomes:
729
730 GC untrack
731 trashcan begin
732 GC track
733
Tim Petersf7f9e992003-11-13 21:59:32 +0000734 Q. Why did the last question say "immediately GC-track again"?
735 It's nowhere near immediately.
736
737 A. Because the code *used* to re-track immediately. Bad Idea.
738 self has a refcount of 0, and if gc ever gets its hands on it
739 (which can happen if any weakref callback gets invoked), it
740 looks like trash to gc too, and gc also tries to delete self
741 then. But we're already deleting self. Double dealloction is
742 a subtle disaster.
743
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000744 Q. Why the bizarre (net-zero) manipulation of
745 _PyTrash_delete_nesting around the trashcan macros?
746
747 A. Some base classes (e.g. list) also use the trashcan mechanism.
748 The following scenario used to be possible:
749
750 - suppose the trashcan level is one below the trashcan limit
751
752 - subtype_dealloc() is called
753
754 - the trashcan limit is not yet reached, so the trashcan level
755 is incremented and the code between trashcan begin and end is
756 executed
757
758 - this destroys much of the object's contents, including its
759 slots and __dict__
760
761 - basedealloc() is called; this is really list_dealloc(), or
762 some other type which also uses the trashcan macros
763
764 - the trashcan limit is now reached, so the object is put on the
765 trashcan's to-be-deleted-later list
766
767 - basedealloc() returns
768
769 - subtype_dealloc() decrefs the object's type
770
771 - subtype_dealloc() returns
772
773 - later, the trashcan code starts deleting the objects from its
774 to-be-deleted-later list
775
776 - subtype_dealloc() is called *AGAIN* for the same object
777
778 - at the very least (if the destroyed slots and __dict__ don't
779 cause problems) the object's type gets decref'ed a second
780 time, which is *BAD*!!!
781
782 The remedy is to make sure that if the code between trashcan
783 begin and end in subtype_dealloc() is called, the code between
784 trashcan begin and end in basedealloc() will also be called.
785 This is done by decrementing the level after passing into the
786 trashcan block, and incrementing it just before leaving the
787 block.
788
789 But now it's possible that a chain of objects consisting solely
790 of objects whose deallocator is subtype_dealloc() will defeat
791 the trashcan mechanism completely: the decremented level means
792 that the effective level never reaches the limit. Therefore, we
793 *increment* the level *before* entering the trashcan block, and
794 matchingly decrement it after leaving. This means the trashcan
795 code will trigger a little early, but that's no big deal.
796
797 Q. Are there any live examples of code in need of all this
798 complexity?
799
800 A. Yes. See SF bug 668433 for code that crashed (when Python was
801 compiled in debug mode) before the trashcan level manipulations
802 were added. For more discussion, see SF patches 581742, 575073
803 and bug 574207.
804 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000805}
806
Jeremy Hylton938ace62002-07-17 16:30:39 +0000807static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809/* type test with subclassing support */
810
811int
812PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
813{
814 PyObject *mro;
815
816 mro = a->tp_mro;
817 if (mro != NULL) {
818 /* Deal with multiple inheritance without recursion
819 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000820 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000821 assert(PyTuple_Check(mro));
822 n = PyTuple_GET_SIZE(mro);
823 for (i = 0; i < n; i++) {
824 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
825 return 1;
826 }
827 return 0;
828 }
829 else {
830 /* a is not completely initilized yet; follow tp_base */
831 do {
832 if (a == b)
833 return 1;
834 a = a->tp_base;
835 } while (a != NULL);
836 return b == &PyBaseObject_Type;
837 }
838}
839
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000840/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000841 without looking in the instance dictionary
842 (so we can't use PyObject_GetAttr) but still binding
843 it to the instance. The arguments are the object,
844 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000845 static variable used to cache the interned Python string.
846
847 Two variants:
848
849 - lookup_maybe() returns NULL without raising an exception
850 when the _PyType_Lookup() call fails;
851
852 - lookup_method() always raises an exception upon errors.
853*/
Guido van Rossum60718732001-08-28 17:47:51 +0000854
855static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000856lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000857{
858 PyObject *res;
859
860 if (*attrobj == NULL) {
861 *attrobj = PyString_InternFromString(attrstr);
862 if (*attrobj == NULL)
863 return NULL;
864 }
865 res = _PyType_Lookup(self->ob_type, *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000866 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000867 descrgetfunc f;
868 if ((f = res->ob_type->tp_descr_get) == NULL)
869 Py_INCREF(res);
870 else
871 res = f(res, self, (PyObject *)(self->ob_type));
872 }
873 return res;
874}
875
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000876static PyObject *
877lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
878{
879 PyObject *res = lookup_maybe(self, attrstr, attrobj);
880 if (res == NULL && !PyErr_Occurred())
881 PyErr_SetObject(PyExc_AttributeError, *attrobj);
882 return res;
883}
884
Guido van Rossum2730b132001-08-28 18:22:14 +0000885/* A variation of PyObject_CallMethod that uses lookup_method()
886 instead of PyObject_GetAttrString(). This uses the same convention
887 as lookup_method to cache the interned name string object. */
888
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000889static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000890call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
891{
892 va_list va;
893 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000894 va_start(va, format);
895
Guido van Rossumda21c012001-10-03 00:50:18 +0000896 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000897 if (func == NULL) {
898 va_end(va);
899 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000900 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000901 return NULL;
902 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000903
904 if (format && *format)
905 args = Py_VaBuildValue(format, va);
906 else
907 args = PyTuple_New(0);
908
909 va_end(va);
910
911 if (args == NULL)
912 return NULL;
913
914 assert(PyTuple_Check(args));
915 retval = PyObject_Call(func, args, NULL);
916
917 Py_DECREF(args);
918 Py_DECREF(func);
919
920 return retval;
921}
922
923/* Clone of call_method() that returns NotImplemented when the lookup fails. */
924
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000925static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000926call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
927{
928 va_list va;
929 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000930 va_start(va, format);
931
Guido van Rossumda21c012001-10-03 00:50:18 +0000932 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000933 if (func == NULL) {
934 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000935 if (!PyErr_Occurred()) {
936 Py_INCREF(Py_NotImplemented);
937 return Py_NotImplemented;
938 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000939 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000940 }
941
942 if (format && *format)
943 args = Py_VaBuildValue(format, va);
944 else
945 args = PyTuple_New(0);
946
947 va_end(va);
948
Guido van Rossum717ce002001-09-14 16:58:08 +0000949 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000950 return NULL;
951
Guido van Rossum717ce002001-09-14 16:58:08 +0000952 assert(PyTuple_Check(args));
953 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000954
955 Py_DECREF(args);
956 Py_DECREF(func);
957
958 return retval;
959}
960
Tim Petersea7f75d2002-12-07 21:39:16 +0000961/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000962 Method resolution order algorithm C3 described in
963 "A Monotonic Superclass Linearization for Dylan",
964 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000965 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000966 (OOPSLA 1996)
967
Guido van Rossum98f33732002-11-25 21:36:54 +0000968 Some notes about the rules implied by C3:
969
Tim Petersea7f75d2002-12-07 21:39:16 +0000970 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000971 It isn't legal to repeat a class in a list of base classes.
972
973 The next three properties are the 3 constraints in "C3".
974
Tim Petersea7f75d2002-12-07 21:39:16 +0000975 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000976 If A precedes B in C's MRO, then A will precede B in the MRO of all
977 subclasses of C.
978
979 Monotonicity.
980 The MRO of a class must be an extension without reordering of the
981 MRO of each of its superclasses.
982
983 Extended Precedence Graph (EPG).
984 Linearization is consistent if there is a path in the EPG from
985 each class to all its successors in the linearization. See
986 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000987 */
988
Tim Petersea7f75d2002-12-07 21:39:16 +0000989static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000990tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000991 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +0000992 size = PyList_GET_SIZE(list);
993
994 for (j = whence+1; j < size; j++) {
995 if (PyList_GET_ITEM(list, j) == o)
996 return 1;
997 }
998 return 0;
999}
1000
Guido van Rossum98f33732002-11-25 21:36:54 +00001001static PyObject *
1002class_name(PyObject *cls)
1003{
1004 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1005 if (name == NULL) {
1006 PyErr_Clear();
1007 Py_XDECREF(name);
1008 name = PyObject_Repr(cls);
1009 }
1010 if (name == NULL)
1011 return NULL;
1012 if (!PyString_Check(name)) {
1013 Py_DECREF(name);
1014 return NULL;
1015 }
1016 return name;
1017}
1018
1019static int
1020check_duplicates(PyObject *list)
1021{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001022 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001023 /* Let's use a quadratic time algorithm,
1024 assuming that the bases lists is short.
1025 */
1026 n = PyList_GET_SIZE(list);
1027 for (i = 0; i < n; i++) {
1028 PyObject *o = PyList_GET_ITEM(list, i);
1029 for (j = i + 1; j < n; j++) {
1030 if (PyList_GET_ITEM(list, j) == o) {
1031 o = class_name(o);
1032 PyErr_Format(PyExc_TypeError,
1033 "duplicate base class %s",
1034 o ? PyString_AS_STRING(o) : "?");
1035 Py_XDECREF(o);
1036 return -1;
1037 }
1038 }
1039 }
1040 return 0;
1041}
1042
1043/* Raise a TypeError for an MRO order disagreement.
1044
1045 It's hard to produce a good error message. In the absence of better
1046 insight into error reporting, report the classes that were candidates
1047 to be put next into the MRO. There is some conflict between the
1048 order in which they should be put in the MRO, but it's hard to
1049 diagnose what constraint can't be satisfied.
1050*/
1051
1052static void
1053set_mro_error(PyObject *to_merge, int *remain)
1054{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001055 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001056 char buf[1000];
1057 PyObject *k, *v;
1058 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001059 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001060
1061 to_merge_size = PyList_GET_SIZE(to_merge);
1062 for (i = 0; i < to_merge_size; i++) {
1063 PyObject *L = PyList_GET_ITEM(to_merge, i);
1064 if (remain[i] < PyList_GET_SIZE(L)) {
1065 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001066 if (PyDict_SetItem(set, c, Py_None) < 0) {
1067 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001068 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001070 }
1071 }
1072 n = PyDict_Size(set);
1073
Raymond Hettingerf394df42003-04-06 19:13:41 +00001074 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1075consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001076 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001077 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001078 PyObject *name = class_name(k);
1079 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1080 name ? PyString_AS_STRING(name) : "?");
1081 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001082 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001083 buf[off++] = ',';
1084 buf[off] = '\0';
1085 }
1086 }
1087 PyErr_SetString(PyExc_TypeError, buf);
1088 Py_DECREF(set);
1089}
1090
Tim Petersea7f75d2002-12-07 21:39:16 +00001091static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001092pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001093 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001094 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001096
Guido van Rossum1f121312002-11-14 19:49:16 +00001097 to_merge_size = PyList_GET_SIZE(to_merge);
1098
Guido van Rossum98f33732002-11-25 21:36:54 +00001099 /* remain stores an index into each sublist of to_merge.
1100 remain[i] is the index of the next base in to_merge[i]
1101 that is not included in acc.
1102 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001104 if (remain == NULL)
1105 return -1;
1106 for (i = 0; i < to_merge_size; i++)
1107 remain[i] = 0;
1108
1109 again:
1110 empty_cnt = 0;
1111 for (i = 0; i < to_merge_size; i++) {
1112 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001113
Guido van Rossum1f121312002-11-14 19:49:16 +00001114 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1115
1116 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1117 empty_cnt++;
1118 continue;
1119 }
1120
Guido van Rossum98f33732002-11-25 21:36:54 +00001121 /* Choose next candidate for MRO.
1122
1123 The input sequences alone can determine the choice.
1124 If not, choose the class which appears in the MRO
1125 of the earliest direct superclass of the new class.
1126 */
1127
Guido van Rossum1f121312002-11-14 19:49:16 +00001128 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1129 for (j = 0; j < to_merge_size; j++) {
1130 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001131 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001132 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001133 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001134 }
1135 ok = PyList_Append(acc, candidate);
1136 if (ok < 0) {
1137 PyMem_Free(remain);
1138 return -1;
1139 }
1140 for (j = 0; j < to_merge_size; j++) {
1141 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001142 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1143 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001144 remain[j]++;
1145 }
1146 }
1147 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001148 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001149 }
1150
Guido van Rossum98f33732002-11-25 21:36:54 +00001151 if (empty_cnt == to_merge_size) {
1152 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001153 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001154 }
1155 set_mro_error(to_merge, remain);
1156 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001157 return -1;
1158}
1159
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160static PyObject *
1161mro_implementation(PyTypeObject *type)
1162{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163 Py_ssize_t i, n;
1164 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001166 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001167
Guido van Rossum63517572002-06-18 16:44:57 +00001168 if(type->tp_dict == NULL) {
1169 if(PyType_Ready(type) < 0)
1170 return NULL;
1171 }
1172
Guido van Rossum98f33732002-11-25 21:36:54 +00001173 /* Find a superclass linearization that honors the constraints
1174 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001175 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001176
1177 to_merge is a list of lists, where each list is a superclass
1178 linearization implied by a base class. The last element of
1179 to_merge is the declared list of bases.
1180 */
1181
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 bases = type->tp_bases;
1183 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001184
1185 to_merge = PyList_New(n+1);
1186 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001188
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001190 PyObject *base = PyTuple_GET_ITEM(bases, i);
1191 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001192 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001194 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001196 }
1197
1198 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001200
1201 bases_aslist = PySequence_List(bases);
1202 if (bases_aslist == NULL) {
1203 Py_DECREF(to_merge);
1204 return NULL;
1205 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001206 /* This is just a basic sanity check. */
1207 if (check_duplicates(bases_aslist) < 0) {
1208 Py_DECREF(to_merge);
1209 Py_DECREF(bases_aslist);
1210 return NULL;
1211 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001212 PyList_SET_ITEM(to_merge, n, bases_aslist);
1213
1214 result = Py_BuildValue("[O]", (PyObject *)type);
1215 if (result == NULL) {
1216 Py_DECREF(to_merge);
1217 return NULL;
1218 }
1219
1220 ok = pmerge(result, to_merge);
1221 Py_DECREF(to_merge);
1222 if (ok < 0) {
1223 Py_DECREF(result);
1224 return NULL;
1225 }
1226
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 return result;
1228}
1229
1230static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001231mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232{
1233 PyTypeObject *type = (PyTypeObject *)self;
1234
Tim Peters6d6c1a32001-08-02 04:15:00 +00001235 return mro_implementation(type);
1236}
1237
1238static int
1239mro_internal(PyTypeObject *type)
1240{
1241 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001242 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243
1244 if (type->ob_type == &PyType_Type) {
1245 result = mro_implementation(type);
1246 }
1247 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001248 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001249 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001250 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001251 if (mro == NULL)
1252 return -1;
1253 result = PyObject_CallObject(mro, NULL);
1254 Py_DECREF(mro);
1255 }
1256 if (result == NULL)
1257 return -1;
1258 tuple = PySequence_Tuple(result);
1259 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001260 if (tuple == NULL)
1261 return -1;
1262 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001263 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001264 PyObject *cls;
1265 PyTypeObject *solid;
1266
1267 solid = solid_base(type);
1268
1269 len = PyTuple_GET_SIZE(tuple);
1270
1271 for (i = 0; i < len; i++) {
1272 PyTypeObject *t;
1273 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001274 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001275 PyErr_Format(PyExc_TypeError,
1276 "mro() returned a non-class ('%.500s')",
1277 cls->ob_type->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001278 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001279 return -1;
1280 }
1281 t = (PyTypeObject*)cls;
1282 if (!PyType_IsSubtype(solid, solid_base(t))) {
1283 PyErr_Format(PyExc_TypeError,
1284 "mro() returned base with unsuitable layout ('%.500s')",
1285 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001286 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001287 return -1;
1288 }
1289 }
1290 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 type->tp_mro = tuple;
1292 return 0;
1293}
1294
1295
1296/* Calculate the best base amongst multiple base classes.
1297 This is the first one that's on the path to the "solid base". */
1298
1299static PyTypeObject *
1300best_base(PyObject *bases)
1301{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001302 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001304 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
1306 assert(PyTuple_Check(bases));
1307 n = PyTuple_GET_SIZE(bases);
1308 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001309 base = NULL;
1310 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001312 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001313 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 PyErr_SetString(
1315 PyExc_TypeError,
1316 "bases must be types");
1317 return NULL;
1318 }
Tim Petersa91e9642001-11-14 23:32:33 +00001319 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001321 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 return NULL;
1323 }
1324 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001325 if (winner == NULL) {
1326 winner = candidate;
1327 base = base_i;
1328 }
1329 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 ;
1331 else if (PyType_IsSubtype(candidate, winner)) {
1332 winner = candidate;
1333 base = base_i;
1334 }
1335 else {
1336 PyErr_SetString(
1337 PyExc_TypeError,
1338 "multiple bases have "
1339 "instance lay-out conflict");
1340 return NULL;
1341 }
1342 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001343 if (base == NULL)
1344 PyErr_SetString(PyExc_TypeError,
1345 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001346 return base;
1347}
1348
1349static int
1350extra_ivars(PyTypeObject *type, PyTypeObject *base)
1351{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001352 size_t t_size = type->tp_basicsize;
1353 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354
Guido van Rossum9676b222001-08-17 20:32:36 +00001355 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 if (type->tp_itemsize || base->tp_itemsize) {
1357 /* If itemsize is involved, stricter rules */
1358 return t_size != b_size ||
1359 type->tp_itemsize != base->tp_itemsize;
1360 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001361 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1362 type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1363 t_size -= sizeof(PyObject *);
1364 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1365 type->tp_dictoffset + sizeof(PyObject *) == t_size)
1366 t_size -= sizeof(PyObject *);
1367
1368 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369}
1370
1371static PyTypeObject *
1372solid_base(PyTypeObject *type)
1373{
1374 PyTypeObject *base;
1375
1376 if (type->tp_base)
1377 base = solid_base(type->tp_base);
1378 else
1379 base = &PyBaseObject_Type;
1380 if (extra_ivars(type, base))
1381 return type;
1382 else
1383 return base;
1384}
1385
Jeremy Hylton938ace62002-07-17 16:30:39 +00001386static void object_dealloc(PyObject *);
1387static int object_init(PyObject *, PyObject *, PyObject *);
1388static int update_slot(PyTypeObject *, PyObject *);
1389static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390
1391static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001392subtype_dict(PyObject *obj, void *context)
1393{
1394 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1395 PyObject *dict;
1396
1397 if (dictptr == NULL) {
1398 PyErr_SetString(PyExc_AttributeError,
1399 "This object has no __dict__");
1400 return NULL;
1401 }
1402 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001403 if (dict == NULL)
1404 *dictptr = dict = PyDict_New();
1405 Py_XINCREF(dict);
1406 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001407}
1408
Guido van Rossum6661be32001-10-26 04:26:12 +00001409static int
1410subtype_setdict(PyObject *obj, PyObject *value, void *context)
1411{
1412 PyObject **dictptr = _PyObject_GetDictPtr(obj);
1413 PyObject *dict;
1414
1415 if (dictptr == NULL) {
1416 PyErr_SetString(PyExc_AttributeError,
1417 "This object has no __dict__");
1418 return -1;
1419 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001420 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001421 PyErr_Format(PyExc_TypeError,
1422 "__dict__ must be set to a dictionary, "
1423 "not a '%.200s'", value->ob_type->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001424 return -1;
1425 }
1426 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001427 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001428 *dictptr = value;
1429 Py_XDECREF(dict);
1430 return 0;
1431}
1432
Guido van Rossumad47da02002-08-12 19:05:44 +00001433static PyObject *
1434subtype_getweakref(PyObject *obj, void *context)
1435{
1436 PyObject **weaklistptr;
1437 PyObject *result;
1438
1439 if (obj->ob_type->tp_weaklistoffset == 0) {
1440 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001441 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001442 return NULL;
1443 }
1444 assert(obj->ob_type->tp_weaklistoffset > 0);
1445 assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001446 (size_t)(obj->ob_type->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001447 weaklistptr = (PyObject **)
Guido van Rossum3747a0f2002-08-12 19:25:08 +00001448 ((char *)obj + obj->ob_type->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001449 if (*weaklistptr == NULL)
1450 result = Py_None;
1451 else
1452 result = *weaklistptr;
1453 Py_INCREF(result);
1454 return result;
1455}
1456
Guido van Rossum373c7412003-01-07 13:41:37 +00001457/* Three variants on the subtype_getsets list. */
1458
1459static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001460 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001461 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001462 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001463 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001464 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001465};
1466
Guido van Rossum373c7412003-01-07 13:41:37 +00001467static PyGetSetDef subtype_getsets_dict_only[] = {
1468 {"__dict__", subtype_dict, subtype_setdict,
1469 PyDoc_STR("dictionary for instance variables (if defined)")},
1470 {0}
1471};
1472
1473static PyGetSetDef subtype_getsets_weakref_only[] = {
1474 {"__weakref__", subtype_getweakref, NULL,
1475 PyDoc_STR("list of weak references to the object (if defined)")},
1476 {0}
1477};
1478
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001479static int
1480valid_identifier(PyObject *s)
1481{
Guido van Rossum03013a02002-07-16 14:30:28 +00001482 unsigned char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001483 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001484
1485 if (!PyString_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001486 PyErr_Format(PyExc_TypeError,
1487 "__slots__ items must be strings, not '%.200s'",
1488 s->ob_type->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001489 return 0;
1490 }
Guido van Rossum03013a02002-07-16 14:30:28 +00001491 p = (unsigned char *) PyString_AS_STRING(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001492 n = PyString_GET_SIZE(s);
1493 /* We must reject an empty name. As a hack, we bump the
1494 length to 1 so that the loop will balk on the trailing \0. */
1495 if (n == 0)
1496 n = 1;
1497 for (i = 0; i < n; i++, p++) {
1498 if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1499 PyErr_SetString(PyExc_TypeError,
1500 "__slots__ must be identifiers");
1501 return 0;
1502 }
1503 }
1504 return 1;
1505}
1506
Martin v. Löwisd919a592002-10-14 21:07:28 +00001507#ifdef Py_USING_UNICODE
1508/* Replace Unicode objects in slots. */
1509
1510static PyObject *
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001511_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
Martin v. Löwisd919a592002-10-14 21:07:28 +00001512{
1513 PyObject *tmp = slots;
1514 PyObject *o, *o1;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001515 Py_ssize_t i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001516 ssizessizeargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
Martin v. Löwisd919a592002-10-14 21:07:28 +00001517 for (i = 0; i < nslots; i++) {
1518 if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1519 if (tmp == slots) {
1520 tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1521 if (tmp == NULL)
1522 return NULL;
1523 }
1524 o1 = _PyUnicode_AsDefaultEncodedString
1525 (o, NULL);
1526 if (o1 == NULL) {
1527 Py_DECREF(tmp);
1528 return 0;
1529 }
1530 Py_INCREF(o1);
1531 Py_DECREF(o);
1532 PyTuple_SET_ITEM(tmp, i, o1);
1533 }
1534 }
1535 return tmp;
1536}
1537#endif
1538
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001539static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1541{
1542 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001543 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001544 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001545 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001546 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001547 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001548 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001549 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001550
Tim Peters3abca122001-10-27 19:37:48 +00001551 assert(args != NULL && PyTuple_Check(args));
1552 assert(kwds == NULL || PyDict_Check(kwds));
1553
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001554 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001555 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001556 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1557 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001558
1559 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1560 PyObject *x = PyTuple_GET_ITEM(args, 0);
1561 Py_INCREF(x->ob_type);
1562 return (PyObject *) x->ob_type;
1563 }
1564
1565 /* SF bug 475327 -- if that didn't trigger, we need 3
1566 arguments. but PyArg_ParseTupleAndKeywords below may give
1567 a msg saying type() needs exactly 3. */
1568 if (nargs + nkwds != 3) {
1569 PyErr_SetString(PyExc_TypeError,
1570 "type() takes 1 or 3 arguments");
1571 return NULL;
1572 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573 }
1574
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001575 /* Check arguments: (name, bases, dict) */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1577 &name,
1578 &PyTuple_Type, &bases,
1579 &PyDict_Type, &dict))
1580 return NULL;
1581
1582 /* Determine the proper metatype to deal with this,
1583 and check for metatype conflicts while we're at it.
1584 Note that if some other metatype wins to contract,
1585 it's possible that its instances are not types. */
1586 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001587 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 for (i = 0; i < nbases; i++) {
1589 tmp = PyTuple_GET_ITEM(bases, i);
1590 tmptype = tmp->ob_type;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001591 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001592 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001593 if (PyType_IsSubtype(tmptype, winner)) {
1594 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001595 continue;
1596 }
1597 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001598 "metaclass conflict: "
1599 "the metaclass of a derived class "
1600 "must be a (non-strict) subclass "
1601 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001602 return NULL;
1603 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001604 if (winner != metatype) {
1605 if (winner->tp_new != type_new) /* Pass it to the winner */
1606 return winner->tp_new(winner, args, kwds);
1607 metatype = winner;
1608 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609
1610 /* Adjust for empty tuple bases */
1611 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001612 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001613 if (bases == NULL)
1614 return NULL;
1615 nbases = 1;
1616 }
1617 else
1618 Py_INCREF(bases);
1619
1620 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1621
1622 /* Calculate best base, and check that all bases are type objects */
1623 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001624 if (base == NULL) {
1625 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001626 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001627 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001628 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1629 PyErr_Format(PyExc_TypeError,
1630 "type '%.100s' is not an acceptable base type",
1631 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001632 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001633 return NULL;
1634 }
1635
Tim Peters6d6c1a32001-08-02 04:15:00 +00001636 /* Check for a __slots__ sequence variable in dict, and count it */
1637 slots = PyDict_GetItemString(dict, "__slots__");
1638 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001639 add_dict = 0;
1640 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001641 may_add_dict = base->tp_dictoffset == 0;
1642 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1643 if (slots == NULL) {
1644 if (may_add_dict) {
1645 add_dict++;
1646 }
1647 if (may_add_weak) {
1648 add_weak++;
1649 }
1650 }
1651 else {
1652 /* Have slots */
1653
Tim Peters6d6c1a32001-08-02 04:15:00 +00001654 /* Make it into a tuple */
1655 if (PyString_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001656 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001657 else
1658 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001659 if (slots == NULL) {
1660 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001661 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001662 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001663 assert(PyTuple_Check(slots));
1664
1665 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001666 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001667 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001668 PyErr_Format(PyExc_TypeError,
1669 "nonempty __slots__ "
1670 "not supported for subtype of '%s'",
1671 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001672 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001673 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001674 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001675 return NULL;
1676 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001677
Martin v. Löwisd919a592002-10-14 21:07:28 +00001678#ifdef Py_USING_UNICODE
1679 tmp = _unicode_to_string(slots, nslots);
Martin v. Löwis13b1a5c2002-10-14 21:11:34 +00001680 if (tmp != slots) {
1681 Py_DECREF(slots);
1682 slots = tmp;
1683 }
Martin v. Löwisd919a592002-10-14 21:07:28 +00001684 if (!tmp)
1685 return NULL;
1686#endif
Guido van Rossumad47da02002-08-12 19:05:44 +00001687 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001688 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001689 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1690 char *s;
1691 if (!valid_identifier(tmp))
1692 goto bad_slots;
1693 assert(PyString_Check(tmp));
1694 s = PyString_AS_STRING(tmp);
1695 if (strcmp(s, "__dict__") == 0) {
1696 if (!may_add_dict || add_dict) {
1697 PyErr_SetString(PyExc_TypeError,
1698 "__dict__ slot disallowed: "
1699 "we already got one");
1700 goto bad_slots;
1701 }
1702 add_dict++;
1703 }
1704 if (strcmp(s, "__weakref__") == 0) {
1705 if (!may_add_weak || add_weak) {
1706 PyErr_SetString(PyExc_TypeError,
1707 "__weakref__ slot disallowed: "
1708 "either we already got one, "
1709 "or __itemsize__ != 0");
1710 goto bad_slots;
1711 }
1712 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713 }
1714 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001715
Guido van Rossumad47da02002-08-12 19:05:44 +00001716 /* Copy slots into yet another tuple, demangling names */
1717 newslots = PyTuple_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001718 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001719 goto bad_slots;
1720 for (i = j = 0; i < nslots; i++) {
1721 char *s;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001722 tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001723 s = PyString_AS_STRING(tmp);
1724 if ((add_dict && strcmp(s, "__dict__") == 0) ||
1725 (add_weak && strcmp(s, "__weakref__") == 0))
1726 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001727 tmp =_Py_Mangle(name, tmp);
1728 if (!tmp)
1729 goto bad_slots;
Guido van Rossumad47da02002-08-12 19:05:44 +00001730 PyTuple_SET_ITEM(newslots, j, tmp);
1731 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001732 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001733 assert(j == nslots - add_dict - add_weak);
1734 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001735 Py_DECREF(slots);
1736 slots = newslots;
1737
Guido van Rossumad47da02002-08-12 19:05:44 +00001738 /* Secondary bases may provide weakrefs or dict */
1739 if (nbases > 1 &&
1740 ((may_add_dict && !add_dict) ||
1741 (may_add_weak && !add_weak))) {
1742 for (i = 0; i < nbases; i++) {
1743 tmp = PyTuple_GET_ITEM(bases, i);
1744 if (tmp == (PyObject *)base)
1745 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001746 assert(PyType_Check(tmp));
1747 tmptype = (PyTypeObject *)tmp;
1748 if (may_add_dict && !add_dict &&
1749 tmptype->tp_dictoffset != 0)
1750 add_dict++;
1751 if (may_add_weak && !add_weak &&
1752 tmptype->tp_weaklistoffset != 0)
1753 add_weak++;
1754 if (may_add_dict && !add_dict)
1755 continue;
1756 if (may_add_weak && !add_weak)
1757 continue;
1758 /* Nothing more to check */
1759 break;
1760 }
1761 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001762 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001763
1764 /* XXX From here until type is safely allocated,
1765 "return NULL" may leak slots! */
1766
1767 /* Allocate the type object */
1768 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001769 if (type == NULL) {
1770 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001771 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001772 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001773 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774
1775 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001776 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001777 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001778 et->ht_name = name;
1779 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001780
Guido van Rossumdc91b992001-08-08 22:26:22 +00001781 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001782 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1783 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001784 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1785 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001786
Guido van Rossumdc91b992001-08-08 22:26:22 +00001787 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001788 type->tp_as_number = &et->as_number;
1789 type->tp_as_sequence = &et->as_sequence;
1790 type->tp_as_mapping = &et->as_mapping;
1791 type->tp_as_buffer = &et->as_buffer;
1792 type->tp_name = PyString_AS_STRING(name);
1793
1794 /* Set tp_base and tp_bases */
1795 type->tp_bases = bases;
1796 Py_INCREF(base);
1797 type->tp_base = base;
1798
Guido van Rossum687ae002001-10-15 22:03:32 +00001799 /* Initialize tp_dict from passed-in dict */
1800 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001801 if (dict == NULL) {
1802 Py_DECREF(type);
1803 return NULL;
1804 }
1805
Guido van Rossumc3542212001-08-16 09:18:56 +00001806 /* Set __module__ in the dict */
1807 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1808 tmp = PyEval_GetGlobals();
1809 if (tmp != NULL) {
1810 tmp = PyDict_GetItemString(tmp, "__name__");
1811 if (tmp != NULL) {
1812 if (PyDict_SetItemString(dict, "__module__",
1813 tmp) < 0)
1814 return NULL;
1815 }
1816 }
1817 }
1818
Tim Peters2f93e282001-10-04 05:27:00 +00001819 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001820 and is a string. The __doc__ accessor will first look for tp_doc;
1821 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001822 */
1823 {
1824 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1825 if (doc != NULL && PyString_Check(doc)) {
1826 const size_t n = (size_t)PyString_GET_SIZE(doc);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001827 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001828 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001829 Py_DECREF(type);
1830 return NULL;
1831 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001832 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
1833 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001834 }
1835 }
1836
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837 /* Special-case __new__: if it's a plain function,
1838 make it a static function */
1839 tmp = PyDict_GetItemString(dict, "__new__");
1840 if (tmp != NULL && PyFunction_Check(tmp)) {
1841 tmp = PyStaticMethod_New(tmp);
1842 if (tmp == NULL) {
1843 Py_DECREF(type);
1844 return NULL;
1845 }
1846 PyDict_SetItemString(dict, "__new__", tmp);
1847 Py_DECREF(tmp);
1848 }
1849
1850 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001851 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001852 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001853 if (slots != NULL) {
1854 for (i = 0; i < nslots; i++, mp++) {
1855 mp->name = PyString_AS_STRING(
1856 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001857 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001858 mp->offset = slotoffset;
Guido van Rossum9676b222001-08-17 20:32:36 +00001859 if (base->tp_weaklistoffset == 0 &&
Guido van Rossum64b206c2001-12-04 17:13:22 +00001860 strcmp(mp->name, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001861 add_weak++;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001862 mp->type = T_OBJECT;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001863 mp->flags = READONLY;
Guido van Rossum9676b222001-08-17 20:32:36 +00001864 type->tp_weaklistoffset = slotoffset;
Guido van Rossum64b206c2001-12-04 17:13:22 +00001865 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001866 slotoffset += sizeof(PyObject *);
1867 }
1868 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001869 if (add_dict) {
1870 if (base->tp_itemsize)
1871 type->tp_dictoffset = -(long)sizeof(PyObject *);
1872 else
1873 type->tp_dictoffset = slotoffset;
1874 slotoffset += sizeof(PyObject *);
1875 }
1876 if (add_weak) {
1877 assert(!base->tp_itemsize);
1878 type->tp_weaklistoffset = slotoffset;
1879 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001880 }
1881 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001882 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001883 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001884
1885 if (type->tp_weaklistoffset && type->tp_dictoffset)
1886 type->tp_getset = subtype_getsets_full;
1887 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1888 type->tp_getset = subtype_getsets_weakref_only;
1889 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1890 type->tp_getset = subtype_getsets_dict_only;
1891 else
1892 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001893
1894 /* Special case some slots */
1895 if (type->tp_dictoffset != 0 || nslots > 0) {
1896 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1897 type->tp_getattro = PyObject_GenericGetAttr;
1898 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1899 type->tp_setattro = PyObject_GenericSetAttr;
1900 }
1901 type->tp_dealloc = subtype_dealloc;
1902
Guido van Rossum9475a232001-10-05 20:51:39 +00001903 /* Enable GC unless there are really no instance variables possible */
1904 if (!(type->tp_basicsize == sizeof(PyObject) &&
1905 type->tp_itemsize == 0))
1906 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1907
Tim Peters6d6c1a32001-08-02 04:15:00 +00001908 /* Always override allocation strategy to use regular heap */
1909 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001910 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001911 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001912 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001913 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001914 }
1915 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001916 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001917
1918 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001919 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001920 Py_DECREF(type);
1921 return NULL;
1922 }
1923
Guido van Rossum7b9144b2001-10-09 19:39:46 +00001924 /* Put the proper slots in place */
1925 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00001926
Tim Peters6d6c1a32001-08-02 04:15:00 +00001927 return (PyObject *)type;
1928}
1929
1930/* Internal API to look for a name through the MRO.
1931 This returns a borrowed reference, and doesn't set an exception! */
1932PyObject *
1933_PyType_Lookup(PyTypeObject *type, PyObject *name)
1934{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001935 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00001936 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001937
Guido van Rossum687ae002001-10-15 22:03:32 +00001938 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001939 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00001940
1941 /* If mro is NULL, the type is either not yet initialized
1942 by PyType_Ready(), or already cleared by type_clear().
1943 Either way the safest thing to do is to return NULL. */
1944 if (mro == NULL)
1945 return NULL;
1946
Tim Peters6d6c1a32001-08-02 04:15:00 +00001947 assert(PyTuple_Check(mro));
1948 n = PyTuple_GET_SIZE(mro);
1949 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001950 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001951 assert(PyType_Check(base));
1952 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 assert(dict && PyDict_Check(dict));
1954 res = PyDict_GetItem(dict, name);
1955 if (res != NULL)
1956 return res;
1957 }
1958 return NULL;
1959}
1960
1961/* This is similar to PyObject_GenericGetAttr(),
1962 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1963static PyObject *
1964type_getattro(PyTypeObject *type, PyObject *name)
1965{
1966 PyTypeObject *metatype = type->ob_type;
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001967 PyObject *meta_attribute, *attribute;
1968 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001969
1970 /* Initialize this type (we'll assume the metatype is initialized) */
1971 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001972 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 return NULL;
1974 }
1975
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001976 /* No readable descriptor found yet */
1977 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001978
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001979 /* Look for the attribute in the metatype */
1980 meta_attribute = _PyType_Lookup(metatype, name);
1981
1982 if (meta_attribute != NULL) {
1983 meta_get = meta_attribute->ob_type->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00001984
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001985 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1986 /* Data descriptors implement tp_descr_set to intercept
1987 * writes. Assume the attribute is not overridden in
1988 * type's tp_dict (and bases): call the descriptor now.
1989 */
1990 return meta_get(meta_attribute, (PyObject *)type,
1991 (PyObject *)metatype);
1992 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001993 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001994 }
1995
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00001996 /* No data descriptor found on metatype. Look in tp_dict of this
1997 * type and its bases */
1998 attribute = _PyType_Lookup(type, name);
1999 if (attribute != NULL) {
2000 /* Implement descriptor functionality, if any */
2001 descrgetfunc local_get = attribute->ob_type->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002002
2003 Py_XDECREF(meta_attribute);
2004
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002005 if (local_get != NULL) {
2006 /* NULL 2nd argument indicates the descriptor was
2007 * found on the target object itself (or a base) */
2008 return local_get(attribute, (PyObject *)NULL,
2009 (PyObject *)type);
2010 }
Tim Peters34592512002-07-11 06:23:50 +00002011
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002012 Py_INCREF(attribute);
2013 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002014 }
2015
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002016 /* No attribute found in local __dict__ (or bases): use the
2017 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002018 if (meta_get != NULL) {
2019 PyObject *res;
2020 res = meta_get(meta_attribute, (PyObject *)type,
2021 (PyObject *)metatype);
2022 Py_DECREF(meta_attribute);
2023 return res;
2024 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002025
2026 /* If an ordinary attribute was found on the metatype, return it now */
2027 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002028 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002029 }
2030
2031 /* Give up */
2032 PyErr_Format(PyExc_AttributeError,
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002033 "type object '%.50s' has no attribute '%.400s'",
2034 type->tp_name, PyString_AS_STRING(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +00002035 return NULL;
2036}
2037
2038static int
2039type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2040{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002041 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2042 PyErr_Format(
2043 PyExc_TypeError,
2044 "can't set attributes of built-in/extension type '%s'",
2045 type->tp_name);
2046 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002047 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002048 /* XXX Example of how I expect this to be used...
2049 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2050 return -1;
2051 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002052 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2053 return -1;
2054 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002055}
2056
2057static void
2058type_dealloc(PyTypeObject *type)
2059{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002060 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002061
2062 /* Assert this is a heap-allocated type object */
2063 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002064 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002065 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002066 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002067 Py_XDECREF(type->tp_base);
2068 Py_XDECREF(type->tp_dict);
2069 Py_XDECREF(type->tp_bases);
2070 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002071 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002072 Py_XDECREF(type->tp_subclasses);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002073 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2074 * of most other objects. It's okay to cast it to char *.
2075 */
2076 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002077 Py_XDECREF(et->ht_name);
2078 Py_XDECREF(et->ht_slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002079 type->ob_type->tp_free((PyObject *)type);
2080}
2081
Guido van Rossum1c450732001-10-08 15:18:27 +00002082static PyObject *
2083type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2084{
2085 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002086 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002087
2088 list = PyList_New(0);
2089 if (list == NULL)
2090 return NULL;
2091 raw = type->tp_subclasses;
2092 if (raw == NULL)
2093 return list;
2094 assert(PyList_Check(raw));
2095 n = PyList_GET_SIZE(raw);
2096 for (i = 0; i < n; i++) {
2097 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002098 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002099 ref = PyWeakref_GET_OBJECT(ref);
2100 if (ref != Py_None) {
2101 if (PyList_Append(list, ref) < 0) {
2102 Py_DECREF(list);
2103 return NULL;
2104 }
2105 }
2106 }
2107 return list;
2108}
2109
Tim Peters6d6c1a32001-08-02 04:15:00 +00002110static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002111 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002112 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002113 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002114 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002115 {0}
2116};
2117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002118PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002119"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002120"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002121
Guido van Rossum048eb752001-10-02 21:24:57 +00002122static int
2123type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2124{
Guido van Rossuma3862092002-06-10 15:24:42 +00002125 /* Because of type_is_gc(), the collector only calls this
2126 for heaptypes. */
2127 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002128
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002129 Py_VISIT(type->tp_dict);
2130 Py_VISIT(type->tp_cache);
2131 Py_VISIT(type->tp_mro);
2132 Py_VISIT(type->tp_bases);
2133 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002134
2135 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002136 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002137 in cycles; tp_subclasses is a list of weak references,
2138 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002139
Guido van Rossum048eb752001-10-02 21:24:57 +00002140 return 0;
2141}
2142
2143static int
2144type_clear(PyTypeObject *type)
2145{
Guido van Rossuma3862092002-06-10 15:24:42 +00002146 /* Because of type_is_gc(), the collector only calls this
2147 for heaptypes. */
2148 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002149
Guido van Rossuma3862092002-06-10 15:24:42 +00002150 /* The only field we need to clear is tp_mro, which is part of a
2151 hard cycle (its first element is the class itself) that won't
2152 be broken otherwise (it's a tuple and tuples don't have a
2153 tp_clear handler). None of the other fields need to be
2154 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002155
Guido van Rossuma3862092002-06-10 15:24:42 +00002156 tp_dict:
2157 It is a dict, so the collector will call its tp_clear.
2158
2159 tp_cache:
2160 Not used; if it were, it would be a dict.
2161
2162 tp_bases, tp_base:
2163 If these are involved in a cycle, there must be at least
2164 one other, mutable object in the cycle, e.g. a base
2165 class's dict; the cycle will be broken that way.
2166
2167 tp_subclasses:
2168 A list of weak references can't be part of a cycle; and
2169 lists have their own tp_clear.
2170
Guido van Rossume5c691a2003-03-07 15:13:17 +00002171 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002172 A tuple of strings can't be part of a cycle.
2173 */
2174
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002175 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002176
2177 return 0;
2178}
2179
2180static int
2181type_is_gc(PyTypeObject *type)
2182{
2183 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2184}
2185
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186PyTypeObject PyType_Type = {
2187 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002188 0, /* ob_size */
2189 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002190 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002191 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192 (destructor)type_dealloc, /* tp_dealloc */
2193 0, /* tp_print */
2194 0, /* tp_getattr */
2195 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002196 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197 (reprfunc)type_repr, /* tp_repr */
2198 0, /* tp_as_number */
2199 0, /* tp_as_sequence */
2200 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002201 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002202 (ternaryfunc)type_call, /* tp_call */
2203 0, /* tp_str */
2204 (getattrofunc)type_getattro, /* tp_getattro */
2205 (setattrofunc)type_setattro, /* tp_setattro */
2206 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002207 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002208 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002209 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002210 (traverseproc)type_traverse, /* tp_traverse */
2211 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002213 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002214 0, /* tp_iter */
2215 0, /* tp_iternext */
2216 type_methods, /* tp_methods */
2217 type_members, /* tp_members */
2218 type_getsets, /* tp_getset */
2219 0, /* tp_base */
2220 0, /* tp_dict */
2221 0, /* tp_descr_get */
2222 0, /* tp_descr_set */
2223 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
2224 0, /* tp_init */
2225 0, /* tp_alloc */
2226 type_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002227 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002228 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002229};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002230
2231
2232/* The base type of all types (eventually)... except itself. */
2233
2234static int
2235object_init(PyObject *self, PyObject *args, PyObject *kwds)
2236{
2237 return 0;
2238}
2239
Guido van Rossum298e4212003-02-13 16:30:16 +00002240/* If we don't have a tp_new for a new-style class, new will use this one.
2241 Therefore this should take no arguments/keywords. However, this new may
2242 also be inherited by objects that define a tp_init but no tp_new. These
2243 objects WILL pass argumets to tp_new, because it gets the same args as
2244 tp_init. So only allow arguments if we aren't using the default init, in
2245 which case we expect init to handle argument parsing. */
2246static PyObject *
2247object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2248{
2249 if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2250 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2251 PyErr_SetString(PyExc_TypeError,
2252 "default __new__ takes no parameters");
2253 return NULL;
2254 }
2255 return type->tp_alloc(type, 0);
2256}
2257
Tim Peters6d6c1a32001-08-02 04:15:00 +00002258static void
2259object_dealloc(PyObject *self)
2260{
2261 self->ob_type->tp_free(self);
2262}
2263
Guido van Rossum8e248182001-08-12 05:17:56 +00002264static PyObject *
2265object_repr(PyObject *self)
2266{
Guido van Rossum76e69632001-08-16 18:52:43 +00002267 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002268 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002269
Guido van Rossum76e69632001-08-16 18:52:43 +00002270 type = self->ob_type;
2271 mod = type_module(type, NULL);
2272 if (mod == NULL)
2273 PyErr_Clear();
2274 else if (!PyString_Check(mod)) {
2275 Py_DECREF(mod);
2276 mod = NULL;
2277 }
2278 name = type_name(type, NULL);
2279 if (name == NULL)
2280 return NULL;
2281 if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002282 rtn = PyString_FromFormat("<%s.%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002283 PyString_AS_STRING(mod),
2284 PyString_AS_STRING(name),
2285 self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002286 else
Guido van Rossumff0e6d62001-09-24 16:03:59 +00002287 rtn = PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002288 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002289 Py_XDECREF(mod);
2290 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002291 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002292}
2293
Guido van Rossumb8f63662001-08-15 23:57:02 +00002294static PyObject *
2295object_str(PyObject *self)
2296{
2297 unaryfunc f;
2298
2299 f = self->ob_type->tp_repr;
2300 if (f == NULL)
2301 f = object_repr;
2302 return f(self);
2303}
2304
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002305static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002306object_richcompare(PyObject *self, PyObject *other, int op)
2307{
2308 PyObject *res;
2309
2310 switch (op) {
2311
2312 case Py_EQ:
2313 res = (self == other) ? Py_True : Py_False;
2314 break;
2315
2316 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002317 /* By default, != returns the opposite of ==,
2318 unless the latter returns NotImplemented. */
2319 res = PyObject_RichCompare(self, other, Py_EQ);
2320 if (res != NULL && res != Py_NotImplemented) {
2321 int ok = PyObject_IsTrue(res);
2322 Py_DECREF(res);
2323 if (ok < 0)
2324 res = NULL;
2325 else {
2326 if (ok)
2327 res = Py_False;
2328 else
2329 res = Py_True;
2330 Py_INCREF(res);
2331 }
2332 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002333 break;
2334
2335 default:
2336 res = Py_NotImplemented;
2337 break;
2338 }
2339
2340 Py_INCREF(res);
2341 return res;
2342}
2343
2344static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002345object_get_class(PyObject *self, void *closure)
2346{
2347 Py_INCREF(self->ob_type);
2348 return (PyObject *)(self->ob_type);
2349}
2350
2351static int
2352equiv_structs(PyTypeObject *a, PyTypeObject *b)
2353{
2354 return a == b ||
2355 (a != NULL &&
2356 b != NULL &&
2357 a->tp_basicsize == b->tp_basicsize &&
2358 a->tp_itemsize == b->tp_itemsize &&
2359 a->tp_dictoffset == b->tp_dictoffset &&
2360 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2361 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2362 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2363}
2364
2365static int
2366same_slots_added(PyTypeObject *a, PyTypeObject *b)
2367{
2368 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002369 Py_ssize_t size;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002370
2371 if (base != b->tp_base)
2372 return 0;
2373 if (equiv_structs(a, base) && equiv_structs(b, base))
2374 return 1;
2375 size = base->tp_basicsize;
2376 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2377 size += sizeof(PyObject *);
2378 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2379 size += sizeof(PyObject *);
2380 return size == a->tp_basicsize && size == b->tp_basicsize;
2381}
2382
2383static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002384compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002385{
2386 PyTypeObject *newbase, *oldbase;
2387
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002388 if (newto->tp_dealloc != oldto->tp_dealloc ||
2389 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002390 {
2391 PyErr_Format(PyExc_TypeError,
2392 "%s assignment: "
2393 "'%s' deallocator differs from '%s'",
2394 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002395 newto->tp_name,
2396 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002397 return 0;
2398 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002399 newbase = newto;
2400 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002401 while (equiv_structs(newbase, newbase->tp_base))
2402 newbase = newbase->tp_base;
2403 while (equiv_structs(oldbase, oldbase->tp_base))
2404 oldbase = oldbase->tp_base;
2405 if (newbase != oldbase &&
2406 (newbase->tp_base != oldbase->tp_base ||
2407 !same_slots_added(newbase, oldbase))) {
2408 PyErr_Format(PyExc_TypeError,
2409 "%s assignment: "
2410 "'%s' object layout differs from '%s'",
2411 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002412 newto->tp_name,
2413 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002414 return 0;
2415 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002416
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002417 return 1;
2418}
2419
2420static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002421object_set_class(PyObject *self, PyObject *value, void *closure)
2422{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002423 PyTypeObject *oldto = self->ob_type;
2424 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002425
Guido van Rossumb6b89422002-04-15 01:03:30 +00002426 if (value == NULL) {
2427 PyErr_SetString(PyExc_TypeError,
2428 "can't delete __class__ attribute");
2429 return -1;
2430 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002431 if (!PyType_Check(value)) {
2432 PyErr_Format(PyExc_TypeError,
2433 "__class__ must be set to new-style class, not '%s' object",
2434 value->ob_type->tp_name);
2435 return -1;
2436 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002437 newto = (PyTypeObject *)value;
2438 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2439 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002440 {
2441 PyErr_Format(PyExc_TypeError,
2442 "__class__ assignment: only for heap types");
2443 return -1;
2444 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002445 if (compatible_for_assignment(newto, oldto, "__class__")) {
2446 Py_INCREF(newto);
2447 self->ob_type = newto;
2448 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002449 return 0;
2450 }
2451 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002452 return -1;
2453 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002454}
2455
2456static PyGetSetDef object_getsets[] = {
2457 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002458 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002459 {0}
2460};
2461
Guido van Rossumc53f0092003-02-18 22:05:12 +00002462
Guido van Rossum036f9992003-02-21 22:02:54 +00002463/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2464 We fall back to helpers in copy_reg for:
2465 - pickle protocols < 2
2466 - calculating the list of slot names (done only once per class)
2467 - the __newobj__ function (which is used as a token but never called)
2468*/
2469
2470static PyObject *
2471import_copy_reg(void)
2472{
2473 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002474
2475 if (!copy_reg_str) {
2476 copy_reg_str = PyString_InternFromString("copy_reg");
2477 if (copy_reg_str == NULL)
2478 return NULL;
2479 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002480
2481 return PyImport_Import(copy_reg_str);
2482}
2483
2484static PyObject *
2485slotnames(PyObject *cls)
2486{
2487 PyObject *clsdict;
2488 PyObject *copy_reg;
2489 PyObject *slotnames;
2490
2491 if (!PyType_Check(cls)) {
2492 Py_INCREF(Py_None);
2493 return Py_None;
2494 }
2495
2496 clsdict = ((PyTypeObject *)cls)->tp_dict;
2497 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002498 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002499 Py_INCREF(slotnames);
2500 return slotnames;
2501 }
2502
2503 copy_reg = import_copy_reg();
2504 if (copy_reg == NULL)
2505 return NULL;
2506
2507 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2508 Py_DECREF(copy_reg);
2509 if (slotnames != NULL &&
2510 slotnames != Py_None &&
2511 !PyList_Check(slotnames))
2512 {
2513 PyErr_SetString(PyExc_TypeError,
2514 "copy_reg._slotnames didn't return a list or None");
2515 Py_DECREF(slotnames);
2516 slotnames = NULL;
2517 }
2518
2519 return slotnames;
2520}
2521
2522static PyObject *
2523reduce_2(PyObject *obj)
2524{
2525 PyObject *cls, *getnewargs;
2526 PyObject *args = NULL, *args2 = NULL;
2527 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2528 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2529 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002530 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002531
2532 cls = PyObject_GetAttrString(obj, "__class__");
2533 if (cls == NULL)
2534 return NULL;
2535
2536 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2537 if (getnewargs != NULL) {
2538 args = PyObject_CallObject(getnewargs, NULL);
2539 Py_DECREF(getnewargs);
2540 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002541 PyErr_Format(PyExc_TypeError,
2542 "__getnewargs__ should return a tuple, "
2543 "not '%.200s'", args->ob_type->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002544 goto end;
2545 }
2546 }
2547 else {
2548 PyErr_Clear();
2549 args = PyTuple_New(0);
2550 }
2551 if (args == NULL)
2552 goto end;
2553
2554 getstate = PyObject_GetAttrString(obj, "__getstate__");
2555 if (getstate != NULL) {
2556 state = PyObject_CallObject(getstate, NULL);
2557 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002558 if (state == NULL)
2559 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002560 }
2561 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002562 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002563 state = PyObject_GetAttrString(obj, "__dict__");
2564 if (state == NULL) {
2565 PyErr_Clear();
2566 state = Py_None;
2567 Py_INCREF(state);
2568 }
2569 names = slotnames(cls);
2570 if (names == NULL)
2571 goto end;
2572 if (names != Py_None) {
2573 assert(PyList_Check(names));
2574 slots = PyDict_New();
2575 if (slots == NULL)
2576 goto end;
2577 n = 0;
2578 /* Can't pre-compute the list size; the list
2579 is stored on the class so accessible to other
2580 threads, which may be run by DECREF */
2581 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2582 PyObject *name, *value;
2583 name = PyList_GET_ITEM(names, i);
2584 value = PyObject_GetAttr(obj, name);
2585 if (value == NULL)
2586 PyErr_Clear();
2587 else {
2588 int err = PyDict_SetItem(slots, name,
2589 value);
2590 Py_DECREF(value);
2591 if (err)
2592 goto end;
2593 n++;
2594 }
2595 }
2596 if (n) {
2597 state = Py_BuildValue("(NO)", state, slots);
2598 if (state == NULL)
2599 goto end;
2600 }
2601 }
2602 }
2603
2604 if (!PyList_Check(obj)) {
2605 listitems = Py_None;
2606 Py_INCREF(listitems);
2607 }
2608 else {
2609 listitems = PyObject_GetIter(obj);
2610 if (listitems == NULL)
2611 goto end;
2612 }
2613
2614 if (!PyDict_Check(obj)) {
2615 dictitems = Py_None;
2616 Py_INCREF(dictitems);
2617 }
2618 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002619 PyObject *items = PyObject_CallMethod(obj, "items", "");
2620 if (items == NULL)
2621 goto end;
2622 dictitems = PyObject_GetIter(items);
2623 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002624 if (dictitems == NULL)
2625 goto end;
2626 }
2627
2628 copy_reg = import_copy_reg();
2629 if (copy_reg == NULL)
2630 goto end;
2631 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2632 if (newobj == NULL)
2633 goto end;
2634
2635 n = PyTuple_GET_SIZE(args);
2636 args2 = PyTuple_New(n+1);
2637 if (args2 == NULL)
2638 goto end;
2639 PyTuple_SET_ITEM(args2, 0, cls);
2640 cls = NULL;
2641 for (i = 0; i < n; i++) {
2642 PyObject *v = PyTuple_GET_ITEM(args, i);
2643 Py_INCREF(v);
2644 PyTuple_SET_ITEM(args2, i+1, v);
2645 }
2646
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002647 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002648
2649 end:
2650 Py_XDECREF(cls);
2651 Py_XDECREF(args);
2652 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002653 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002654 Py_XDECREF(state);
2655 Py_XDECREF(names);
2656 Py_XDECREF(listitems);
2657 Py_XDECREF(dictitems);
2658 Py_XDECREF(copy_reg);
2659 Py_XDECREF(newobj);
2660 return res;
2661}
2662
2663static PyObject *
2664object_reduce_ex(PyObject *self, PyObject *args)
2665{
2666 /* Call copy_reg._reduce_ex(self, proto) */
2667 PyObject *reduce, *copy_reg, *res;
2668 int proto = 0;
2669
2670 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2671 return NULL;
2672
2673 reduce = PyObject_GetAttrString(self, "__reduce__");
2674 if (reduce == NULL)
2675 PyErr_Clear();
2676 else {
2677 PyObject *cls, *clsreduce, *objreduce;
2678 int override;
2679 cls = PyObject_GetAttrString(self, "__class__");
2680 if (cls == NULL) {
2681 Py_DECREF(reduce);
2682 return NULL;
2683 }
2684 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2685 Py_DECREF(cls);
2686 if (clsreduce == NULL) {
2687 Py_DECREF(reduce);
2688 return NULL;
2689 }
2690 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2691 "__reduce__");
2692 override = (clsreduce != objreduce);
2693 Py_DECREF(clsreduce);
2694 if (override) {
2695 res = PyObject_CallObject(reduce, NULL);
2696 Py_DECREF(reduce);
2697 return res;
2698 }
2699 else
2700 Py_DECREF(reduce);
2701 }
2702
2703 if (proto >= 2)
2704 return reduce_2(self);
2705
2706 copy_reg = import_copy_reg();
Guido van Rossum3926a632001-09-25 16:25:58 +00002707 if (!copy_reg)
2708 return NULL;
Guido van Rossum036f9992003-02-21 22:02:54 +00002709
Guido van Rossumc53f0092003-02-18 22:05:12 +00002710 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002711 Py_DECREF(copy_reg);
Guido van Rossum036f9992003-02-21 22:02:54 +00002712
Guido van Rossum3926a632001-09-25 16:25:58 +00002713 return res;
2714}
2715
2716static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002717 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2718 PyDoc_STR("helper for pickle")},
2719 {"__reduce__", object_reduce_ex, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002720 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002721 {0}
2722};
2723
Guido van Rossum036f9992003-02-21 22:02:54 +00002724
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725PyTypeObject PyBaseObject_Type = {
2726 PyObject_HEAD_INIT(&PyType_Type)
2727 0, /* ob_size */
2728 "object", /* tp_name */
2729 sizeof(PyObject), /* tp_basicsize */
2730 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002731 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002732 0, /* tp_print */
2733 0, /* tp_getattr */
2734 0, /* tp_setattr */
2735 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002736 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002737 0, /* tp_as_number */
2738 0, /* tp_as_sequence */
2739 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002740 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002741 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002742 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002743 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002744 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745 0, /* tp_as_buffer */
2746 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002747 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002748 0, /* tp_traverse */
2749 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002750 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002751 0, /* tp_weaklistoffset */
2752 0, /* tp_iter */
2753 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002754 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002755 0, /* tp_members */
2756 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002757 0, /* tp_base */
2758 0, /* tp_dict */
2759 0, /* tp_descr_get */
2760 0, /* tp_descr_set */
2761 0, /* tp_dictoffset */
2762 object_init, /* tp_init */
2763 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002764 object_new, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002765 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766};
2767
2768
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002769/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002770
2771static int
2772add_methods(PyTypeObject *type, PyMethodDef *meth)
2773{
Guido van Rossum687ae002001-10-15 22:03:32 +00002774 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002775
2776 for (; meth->ml_name != NULL; meth++) {
2777 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002778 if (PyDict_GetItemString(dict, meth->ml_name) &&
2779 !(meth->ml_flags & METH_COEXIST))
2780 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002781 if (meth->ml_flags & METH_CLASS) {
2782 if (meth->ml_flags & METH_STATIC) {
2783 PyErr_SetString(PyExc_ValueError,
2784 "method cannot be both class and static");
2785 return -1;
2786 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002787 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002788 }
2789 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002790 PyObject *cfunc = PyCFunction_New(meth, NULL);
2791 if (cfunc == NULL)
2792 return -1;
2793 descr = PyStaticMethod_New(cfunc);
2794 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00002795 }
2796 else {
2797 descr = PyDescr_NewMethod(type, meth);
2798 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002799 if (descr == NULL)
2800 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00002801 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002802 return -1;
2803 Py_DECREF(descr);
2804 }
2805 return 0;
2806}
2807
2808static int
Guido van Rossum6f799372001-09-20 20:46:19 +00002809add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002810{
Guido van Rossum687ae002001-10-15 22:03:32 +00002811 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002812
2813 for (; memb->name != NULL; memb++) {
2814 PyObject *descr;
2815 if (PyDict_GetItemString(dict, memb->name))
2816 continue;
2817 descr = PyDescr_NewMember(type, memb);
2818 if (descr == NULL)
2819 return -1;
2820 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2821 return -1;
2822 Py_DECREF(descr);
2823 }
2824 return 0;
2825}
2826
2827static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00002828add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002829{
Guido van Rossum687ae002001-10-15 22:03:32 +00002830 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002831
2832 for (; gsp->name != NULL; gsp++) {
2833 PyObject *descr;
2834 if (PyDict_GetItemString(dict, gsp->name))
2835 continue;
2836 descr = PyDescr_NewGetSet(type, gsp);
2837
2838 if (descr == NULL)
2839 return -1;
2840 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2841 return -1;
2842 Py_DECREF(descr);
2843 }
2844 return 0;
2845}
2846
Guido van Rossum13d52f02001-08-10 21:24:08 +00002847static void
2848inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002849{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002850 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002851
Guido van Rossum13d52f02001-08-10 21:24:08 +00002852 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00002853 oldsize = base->tp_basicsize;
2854 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2855 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2856 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00002857 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00002858 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002859 if (type->tp_traverse == NULL)
2860 type->tp_traverse = base->tp_traverse;
2861 if (type->tp_clear == NULL)
2862 type->tp_clear = base->tp_clear;
2863 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002864 {
Guido van Rossumf884b742001-12-17 17:14:22 +00002865 /* The condition below could use some explanation.
2866 It appears that tp_new is not inherited for static types
2867 whose base class is 'object'; this seems to be a precaution
2868 so that old extension types don't suddenly become
2869 callable (object.__new__ wouldn't insure the invariants
2870 that the extension type's own factory function ensures).
2871 Heap types, of course, are under our control, so they do
2872 inherit tp_new; static extension types that specify some
2873 other built-in type as the default are considered
2874 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002875 if (base != &PyBaseObject_Type ||
2876 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2877 if (type->tp_new == NULL)
2878 type->tp_new = base->tp_new;
2879 }
2880 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00002881 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00002882
2883 /* Copy other non-function slots */
2884
2885#undef COPYVAL
2886#define COPYVAL(SLOT) \
2887 if (type->SLOT == 0) type->SLOT = base->SLOT
2888
2889 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002890 COPYVAL(tp_weaklistoffset);
2891 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00002892
2893 /* Setup fast subclass flags */
2894 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
2895 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
2896 else if (PyType_IsSubtype(base, &PyType_Type))
2897 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
2898 else if (PyType_IsSubtype(base, &PyLong_Type))
2899 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
2900 else if (PyType_IsSubtype(base, &PyString_Type))
2901 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
2902 else if (PyType_IsSubtype(base, &PyUnicode_Type))
2903 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
2904 else if (PyType_IsSubtype(base, &PyTuple_Type))
2905 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
2906 else if (PyType_IsSubtype(base, &PyList_Type))
2907 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
2908 else if (PyType_IsSubtype(base, &PyDict_Type))
2909 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00002910}
2911
Guido van Rossum38938152006-08-21 23:36:26 +00002912/* Map rich comparison operators to their __xx__ namesakes */
2913static char *name_op[] = {
2914 "__lt__",
2915 "__le__",
2916 "__eq__",
2917 "__ne__",
2918 "__gt__",
2919 "__ge__",
2920 /* These are only for overrides_cmp_or_hash(): */
2921 "__cmp__",
2922 "__hash__",
2923};
2924
2925static int
2926overrides_cmp_or_hash(PyTypeObject *type)
2927{
2928 int i;
2929 PyObject *dict = type->tp_dict;
2930
2931 assert(dict != NULL);
2932 for (i = 0; i < 8; i++) {
2933 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
2934 return 1;
2935 }
2936 return 0;
2937}
2938
Guido van Rossum13d52f02001-08-10 21:24:08 +00002939static void
2940inherit_slots(PyTypeObject *type, PyTypeObject *base)
2941{
2942 PyTypeObject *basebase;
2943
2944#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945#undef COPYSLOT
2946#undef COPYNUM
2947#undef COPYSEQ
2948#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00002949#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00002950
2951#define SLOTDEFINED(SLOT) \
2952 (base->SLOT != 0 && \
2953 (basebase == NULL || base->SLOT != basebase->SLOT))
2954
Tim Peters6d6c1a32001-08-02 04:15:00 +00002955#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00002956 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00002957
2958#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2959#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2960#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00002961#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002962
Guido van Rossum13d52f02001-08-10 21:24:08 +00002963 /* This won't inherit indirect slots (from tp_as_number etc.)
2964 if type doesn't provide the space. */
2965
2966 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2967 basebase = base->tp_base;
2968 if (basebase->tp_as_number == NULL)
2969 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002970 COPYNUM(nb_add);
2971 COPYNUM(nb_subtract);
2972 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002973 COPYNUM(nb_remainder);
2974 COPYNUM(nb_divmod);
2975 COPYNUM(nb_power);
2976 COPYNUM(nb_negative);
2977 COPYNUM(nb_positive);
2978 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00002979 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002980 COPYNUM(nb_invert);
2981 COPYNUM(nb_lshift);
2982 COPYNUM(nb_rshift);
2983 COPYNUM(nb_and);
2984 COPYNUM(nb_xor);
2985 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986 COPYNUM(nb_int);
2987 COPYNUM(nb_long);
2988 COPYNUM(nb_float);
2989 COPYNUM(nb_oct);
2990 COPYNUM(nb_hex);
2991 COPYNUM(nb_inplace_add);
2992 COPYNUM(nb_inplace_subtract);
2993 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002994 COPYNUM(nb_inplace_remainder);
2995 COPYNUM(nb_inplace_power);
2996 COPYNUM(nb_inplace_lshift);
2997 COPYNUM(nb_inplace_rshift);
2998 COPYNUM(nb_inplace_and);
2999 COPYNUM(nb_inplace_xor);
3000 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003001 COPYNUM(nb_true_divide);
3002 COPYNUM(nb_floor_divide);
3003 COPYNUM(nb_inplace_true_divide);
3004 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003005 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006 }
3007
Guido van Rossum13d52f02001-08-10 21:24:08 +00003008 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3009 basebase = base->tp_base;
3010 if (basebase->tp_as_sequence == NULL)
3011 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003012 COPYSEQ(sq_length);
3013 COPYSEQ(sq_concat);
3014 COPYSEQ(sq_repeat);
3015 COPYSEQ(sq_item);
3016 COPYSEQ(sq_slice);
3017 COPYSEQ(sq_ass_item);
3018 COPYSEQ(sq_ass_slice);
3019 COPYSEQ(sq_contains);
3020 COPYSEQ(sq_inplace_concat);
3021 COPYSEQ(sq_inplace_repeat);
3022 }
3023
Guido van Rossum13d52f02001-08-10 21:24:08 +00003024 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3025 basebase = base->tp_base;
3026 if (basebase->tp_as_mapping == NULL)
3027 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003028 COPYMAP(mp_length);
3029 COPYMAP(mp_subscript);
3030 COPYMAP(mp_ass_subscript);
3031 }
3032
Tim Petersfc57ccb2001-10-12 02:38:24 +00003033 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3034 basebase = base->tp_base;
3035 if (basebase->tp_as_buffer == NULL)
3036 basebase = NULL;
3037 COPYBUF(bf_getreadbuffer);
3038 COPYBUF(bf_getwritebuffer);
3039 COPYBUF(bf_getsegcount);
3040 COPYBUF(bf_getcharbuffer);
3041 }
3042
Guido van Rossum13d52f02001-08-10 21:24:08 +00003043 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003044
Tim Peters6d6c1a32001-08-02 04:15:00 +00003045 COPYSLOT(tp_dealloc);
3046 COPYSLOT(tp_print);
3047 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3048 type->tp_getattr = base->tp_getattr;
3049 type->tp_getattro = base->tp_getattro;
3050 }
3051 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3052 type->tp_setattr = base->tp_setattr;
3053 type->tp_setattro = base->tp_setattro;
3054 }
3055 /* tp_compare see tp_richcompare */
3056 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003057 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003058 COPYSLOT(tp_call);
3059 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003060 {
Guido van Rossum38938152006-08-21 23:36:26 +00003061 /* Copy comparison-related slots only when
3062 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003063 if (type->tp_compare == NULL &&
3064 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003065 type->tp_hash == NULL &&
3066 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003067 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003068 type->tp_compare = base->tp_compare;
3069 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003070 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003071 }
3072 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003073 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003074 COPYSLOT(tp_iter);
3075 COPYSLOT(tp_iternext);
3076 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003077 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003078 COPYSLOT(tp_descr_get);
3079 COPYSLOT(tp_descr_set);
3080 COPYSLOT(tp_dictoffset);
3081 COPYSLOT(tp_init);
3082 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003083 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003084 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3085 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3086 /* They agree about gc. */
3087 COPYSLOT(tp_free);
3088 }
3089 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3090 type->tp_free == NULL &&
3091 base->tp_free == _PyObject_Del) {
3092 /* A bit of magic to plug in the correct default
3093 * tp_free function when a derived class adds gc,
3094 * didn't define tp_free, and the base uses the
3095 * default non-gc tp_free.
3096 */
3097 type->tp_free = PyObject_GC_Del;
3098 }
3099 /* else they didn't agree about gc, and there isn't something
3100 * obvious to be done -- the type is on its own.
3101 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003102 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003103}
3104
Jeremy Hylton938ace62002-07-17 16:30:39 +00003105static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003106
Tim Peters6d6c1a32001-08-02 04:15:00 +00003107int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003108PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003109{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003110 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003111 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003112 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003113
Guido van Rossumcab05802002-06-10 15:29:03 +00003114 if (type->tp_flags & Py_TPFLAGS_READY) {
3115 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003116 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003117 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003118 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003119
3120 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003121
Tim Peters36eb4df2003-03-23 03:33:13 +00003122#ifdef Py_TRACE_REFS
3123 /* PyType_Ready is the closest thing we have to a choke point
3124 * for type objects, so is the best place I can think of to try
3125 * to get type objects into the doubly-linked list of all objects.
3126 * Still, not all type objects go thru PyType_Ready.
3127 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003128 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003129#endif
3130
Tim Peters6d6c1a32001-08-02 04:15:00 +00003131 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3132 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003133 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003134 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003135 Py_INCREF(base);
3136 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003137
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003138 /* Now the only way base can still be NULL is if type is
3139 * &PyBaseObject_Type.
3140 */
3141
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003142 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003143 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003144 if (PyType_Ready(base) < 0)
3145 goto error;
3146 }
3147
Guido van Rossum0986d822002-04-08 01:38:42 +00003148 /* Initialize ob_type if NULL. This means extensions that want to be
3149 compilable separately on Windows can call PyType_Ready() instead of
3150 initializing the ob_type field of their type objects. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003151 /* The test for base != NULL is really unnecessary, since base is only
3152 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3153 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3154 know that. */
3155 if (type->ob_type == NULL && base != NULL)
Guido van Rossum0986d822002-04-08 01:38:42 +00003156 type->ob_type = base->ob_type;
3157
Tim Peters6d6c1a32001-08-02 04:15:00 +00003158 /* Initialize tp_bases */
3159 bases = type->tp_bases;
3160 if (bases == NULL) {
3161 if (base == NULL)
3162 bases = PyTuple_New(0);
3163 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003164 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003166 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003167 type->tp_bases = bases;
3168 }
3169
Guido van Rossum687ae002001-10-15 22:03:32 +00003170 /* Initialize tp_dict */
3171 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003172 if (dict == NULL) {
3173 dict = PyDict_New();
3174 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003175 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003176 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003177 }
3178
Guido van Rossum687ae002001-10-15 22:03:32 +00003179 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003180 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003181 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003182 if (type->tp_methods != NULL) {
3183 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003184 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003185 }
3186 if (type->tp_members != NULL) {
3187 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003188 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003189 }
3190 if (type->tp_getset != NULL) {
3191 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003192 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003193 }
3194
Tim Peters6d6c1a32001-08-02 04:15:00 +00003195 /* Calculate method resolution order */
3196 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003197 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003198 }
3199
Guido van Rossum13d52f02001-08-10 21:24:08 +00003200 /* Inherit special flags from dominant base */
3201 if (type->tp_base != NULL)
3202 inherit_special(type, type->tp_base);
3203
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003205 bases = type->tp_mro;
3206 assert(bases != NULL);
3207 assert(PyTuple_Check(bases));
3208 n = PyTuple_GET_SIZE(bases);
3209 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003210 PyObject *b = PyTuple_GET_ITEM(bases, i);
3211 if (PyType_Check(b))
3212 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003213 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003214
Tim Peters3cfe7542003-05-21 21:29:48 +00003215 /* Sanity check for tp_free. */
3216 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3217 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
3218 /* This base class needs to call tp_free, but doesn't have
3219 * one, or its tp_free is for non-gc'ed objects.
3220 */
3221 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3222 "gc and is a base type but has inappropriate "
3223 "tp_free slot",
3224 type->tp_name);
3225 goto error;
3226 }
3227
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003228 /* if the type dictionary doesn't contain a __doc__, set it from
3229 the tp_doc slot.
3230 */
3231 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3232 if (type->tp_doc != NULL) {
3233 PyObject *doc = PyString_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003234 if (doc == NULL)
3235 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003236 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3237 Py_DECREF(doc);
3238 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003239 PyDict_SetItemString(type->tp_dict,
3240 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003241 }
3242 }
3243
Guido van Rossum38938152006-08-21 23:36:26 +00003244 /* Hack for tp_hash and __hash__.
3245 If after all that, tp_hash is still NULL, and __hash__ is not in
3246 tp_dict, set tp_dict['__hash__'] equal to None.
3247 This signals that __hash__ is not inherited.
3248 */
3249 if (type->tp_hash == NULL) {
3250 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3251 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3252 goto error;
3253 }
3254 }
3255
Guido van Rossum13d52f02001-08-10 21:24:08 +00003256 /* Some more special stuff */
3257 base = type->tp_base;
3258 if (base != NULL) {
3259 if (type->tp_as_number == NULL)
3260 type->tp_as_number = base->tp_as_number;
3261 if (type->tp_as_sequence == NULL)
3262 type->tp_as_sequence = base->tp_as_sequence;
3263 if (type->tp_as_mapping == NULL)
3264 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003265 if (type->tp_as_buffer == NULL)
3266 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003267 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003268
Guido van Rossum1c450732001-10-08 15:18:27 +00003269 /* Link into each base class's list of subclasses */
3270 bases = type->tp_bases;
3271 n = PyTuple_GET_SIZE(bases);
3272 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003273 PyObject *b = PyTuple_GET_ITEM(bases, i);
3274 if (PyType_Check(b) &&
3275 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003276 goto error;
3277 }
3278
Guido van Rossum13d52f02001-08-10 21:24:08 +00003279 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003280 assert(type->tp_dict != NULL);
3281 type->tp_flags =
3282 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003283 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003284
3285 error:
3286 type->tp_flags &= ~Py_TPFLAGS_READYING;
3287 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003288}
3289
Guido van Rossum1c450732001-10-08 15:18:27 +00003290static int
3291add_subclass(PyTypeObject *base, PyTypeObject *type)
3292{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003293 Py_ssize_t i;
3294 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003295 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003296
3297 list = base->tp_subclasses;
3298 if (list == NULL) {
3299 base->tp_subclasses = list = PyList_New(0);
3300 if (list == NULL)
3301 return -1;
3302 }
3303 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003304 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003305 i = PyList_GET_SIZE(list);
3306 while (--i >= 0) {
3307 ref = PyList_GET_ITEM(list, i);
3308 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003309 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003310 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003311 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003312 result = PyList_Append(list, newobj);
3313 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003314 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003315}
3316
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003317static void
3318remove_subclass(PyTypeObject *base, PyTypeObject *type)
3319{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003320 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003321 PyObject *list, *ref;
3322
3323 list = base->tp_subclasses;
3324 if (list == NULL) {
3325 return;
3326 }
3327 assert(PyList_Check(list));
3328 i = PyList_GET_SIZE(list);
3329 while (--i >= 0) {
3330 ref = PyList_GET_ITEM(list, i);
3331 assert(PyWeakref_CheckRef(ref));
3332 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3333 /* this can't fail, right? */
3334 PySequence_DelItem(list, i);
3335 return;
3336 }
3337 }
3338}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003339
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003340static int
3341check_num_args(PyObject *ob, int n)
3342{
3343 if (!PyTuple_CheckExact(ob)) {
3344 PyErr_SetString(PyExc_SystemError,
3345 "PyArg_UnpackTuple() argument list is not a tuple");
3346 return 0;
3347 }
3348 if (n == PyTuple_GET_SIZE(ob))
3349 return 1;
3350 PyErr_Format(
3351 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003352 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003353 return 0;
3354}
3355
Tim Peters6d6c1a32001-08-02 04:15:00 +00003356/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3357
3358/* There's a wrapper *function* for each distinct function typedef used
3359 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
3360 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3361 Most tables have only one entry; the tables for binary operators have two
3362 entries, one regular and one with reversed arguments. */
3363
3364static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003365wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003367 lenfunc func = (lenfunc)wrapped;
3368 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003369
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003370 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371 return NULL;
3372 res = (*func)(self);
3373 if (res == -1 && PyErr_Occurred())
3374 return NULL;
3375 return PyInt_FromLong((long)res);
3376}
3377
Tim Peters6d6c1a32001-08-02 04:15:00 +00003378static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003379wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3380{
3381 inquiry func = (inquiry)wrapped;
3382 int res;
3383
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003384 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003385 return NULL;
3386 res = (*func)(self);
3387 if (res == -1 && PyErr_Occurred())
3388 return NULL;
3389 return PyBool_FromLong((long)res);
3390}
3391
3392static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003393wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3394{
3395 binaryfunc func = (binaryfunc)wrapped;
3396 PyObject *other;
3397
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003398 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003400 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003401 return (*func)(self, other);
3402}
3403
3404static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003405wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3406{
3407 binaryfunc func = (binaryfunc)wrapped;
3408 PyObject *other;
3409
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003410 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003411 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003412 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003413 return (*func)(self, other);
3414}
3415
3416static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003417wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3418{
3419 binaryfunc func = (binaryfunc)wrapped;
3420 PyObject *other;
3421
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003422 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003423 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003424 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003425 if (!PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003426 Py_INCREF(Py_NotImplemented);
3427 return Py_NotImplemented;
3428 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003429 return (*func)(other, self);
3430}
3431
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003432static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003433wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3434{
3435 ternaryfunc func = (ternaryfunc)wrapped;
3436 PyObject *other;
3437 PyObject *third = Py_None;
3438
3439 /* Note: This wrapper only works for __pow__() */
3440
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003441 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442 return NULL;
3443 return (*func)(self, other, third);
3444}
3445
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003446static PyObject *
3447wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3448{
3449 ternaryfunc func = (ternaryfunc)wrapped;
3450 PyObject *other;
3451 PyObject *third = Py_None;
3452
3453 /* Note: This wrapper only works for __pow__() */
3454
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003455 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003456 return NULL;
3457 return (*func)(other, self, third);
3458}
3459
Tim Peters6d6c1a32001-08-02 04:15:00 +00003460static PyObject *
3461wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3462{
3463 unaryfunc func = (unaryfunc)wrapped;
3464
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003465 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003466 return NULL;
3467 return (*func)(self);
3468}
3469
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003471wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003472{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003473 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003474 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003475 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003476
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003477 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3478 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003479 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003480 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481 return NULL;
3482 return (*func)(self, i);
3483}
3484
Martin v. Löwis18e16552006-02-15 17:27:45 +00003485static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003486getindex(PyObject *self, PyObject *arg)
3487{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003488 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003489
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003490 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003491 if (i == -1 && PyErr_Occurred())
3492 return -1;
3493 if (i < 0) {
3494 PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3495 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003496 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003497 if (n < 0)
3498 return -1;
3499 i += n;
3500 }
3501 }
3502 return i;
3503}
3504
3505static PyObject *
3506wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3507{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003508 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003509 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003510 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003511
Guido van Rossumf4593e02001-10-03 12:09:30 +00003512 if (PyTuple_GET_SIZE(args) == 1) {
3513 arg = PyTuple_GET_ITEM(args, 0);
3514 i = getindex(self, arg);
3515 if (i == -1 && PyErr_Occurred())
3516 return NULL;
3517 return (*func)(self, i);
3518 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003519 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003520 assert(PyErr_Occurred());
3521 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003522}
3523
Tim Peters6d6c1a32001-08-02 04:15:00 +00003524static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003525wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003526{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003527 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3528 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003529
Martin v. Löwis18e16552006-02-15 17:27:45 +00003530 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003531 return NULL;
3532 return (*func)(self, i, j);
3533}
3534
Tim Peters6d6c1a32001-08-02 04:15:00 +00003535static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003536wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003538 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3539 Py_ssize_t i;
3540 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003541 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003542
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003543 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003544 return NULL;
3545 i = getindex(self, arg);
3546 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003547 return NULL;
3548 res = (*func)(self, i, value);
3549 if (res == -1 && PyErr_Occurred())
3550 return NULL;
3551 Py_INCREF(Py_None);
3552 return Py_None;
3553}
3554
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003555static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003556wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003557{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003558 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3559 Py_ssize_t i;
3560 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003561 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003562
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003563 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003564 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003565 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003566 i = getindex(self, arg);
3567 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003568 return NULL;
3569 res = (*func)(self, i, NULL);
3570 if (res == -1 && PyErr_Occurred())
3571 return NULL;
3572 Py_INCREF(Py_None);
3573 return Py_None;
3574}
3575
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003577wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003578{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003579 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3580 Py_ssize_t i, j;
3581 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003582 PyObject *value;
3583
Martin v. Löwis18e16552006-02-15 17:27:45 +00003584 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585 return NULL;
3586 res = (*func)(self, i, j, value);
3587 if (res == -1 && PyErr_Occurred())
3588 return NULL;
3589 Py_INCREF(Py_None);
3590 return Py_None;
3591}
3592
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003593static PyObject *
3594wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3595{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003596 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3597 Py_ssize_t i, j;
3598 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003599
Martin v. Löwis18e16552006-02-15 17:27:45 +00003600 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003601 return NULL;
3602 res = (*func)(self, i, j, NULL);
3603 if (res == -1 && PyErr_Occurred())
3604 return NULL;
3605 Py_INCREF(Py_None);
3606 return Py_None;
3607}
3608
Tim Peters6d6c1a32001-08-02 04:15:00 +00003609/* XXX objobjproc is a misnomer; should be objargpred */
3610static PyObject *
3611wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3612{
3613 objobjproc func = (objobjproc)wrapped;
3614 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003615 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003616
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003617 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003619 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003620 res = (*func)(self, value);
3621 if (res == -1 && PyErr_Occurred())
3622 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003623 else
3624 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003625}
3626
Tim Peters6d6c1a32001-08-02 04:15:00 +00003627static PyObject *
3628wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3629{
3630 objobjargproc func = (objobjargproc)wrapped;
3631 int res;
3632 PyObject *key, *value;
3633
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003634 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003635 return NULL;
3636 res = (*func)(self, key, value);
3637 if (res == -1 && PyErr_Occurred())
3638 return NULL;
3639 Py_INCREF(Py_None);
3640 return Py_None;
3641}
3642
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003643static PyObject *
3644wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3645{
3646 objobjargproc func = (objobjargproc)wrapped;
3647 int res;
3648 PyObject *key;
3649
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003650 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003651 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003652 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003653 res = (*func)(self, key, NULL);
3654 if (res == -1 && PyErr_Occurred())
3655 return NULL;
3656 Py_INCREF(Py_None);
3657 return Py_None;
3658}
3659
Tim Peters6d6c1a32001-08-02 04:15:00 +00003660static PyObject *
3661wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3662{
3663 cmpfunc func = (cmpfunc)wrapped;
3664 int res;
3665 PyObject *other;
3666
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003667 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003668 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003669 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum3d45d8f2001-09-24 18:47:40 +00003670 if (other->ob_type->tp_compare != func &&
3671 !PyType_IsSubtype(other->ob_type, self->ob_type)) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003672 PyErr_Format(
3673 PyExc_TypeError,
3674 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3675 self->ob_type->tp_name,
3676 self->ob_type->tp_name,
3677 other->ob_type->tp_name);
3678 return NULL;
3679 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003680 res = (*func)(self, other);
3681 if (PyErr_Occurred())
3682 return NULL;
3683 return PyInt_FromLong((long)res);
3684}
3685
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003686/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003687 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003688static int
3689hackcheck(PyObject *self, setattrofunc func, char *what)
3690{
3691 PyTypeObject *type = self->ob_type;
3692 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3693 type = type->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003694 /* If type is NULL now, this is a really weird type.
Thomas Wouters89f507f2006-12-13 04:49:30 +00003695 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003696 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003697 PyErr_Format(PyExc_TypeError,
3698 "can't apply this %s to %s object",
3699 what,
3700 type->tp_name);
3701 return 0;
3702 }
3703 return 1;
3704}
3705
Tim Peters6d6c1a32001-08-02 04:15:00 +00003706static PyObject *
3707wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3708{
3709 setattrofunc func = (setattrofunc)wrapped;
3710 int res;
3711 PyObject *name, *value;
3712
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003713 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003715 if (!hackcheck(self, func, "__setattr__"))
3716 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003717 res = (*func)(self, name, value);
3718 if (res < 0)
3719 return NULL;
3720 Py_INCREF(Py_None);
3721 return Py_None;
3722}
3723
3724static PyObject *
3725wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3726{
3727 setattrofunc func = (setattrofunc)wrapped;
3728 int res;
3729 PyObject *name;
3730
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003731 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003733 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003734 if (!hackcheck(self, func, "__delattr__"))
3735 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003736 res = (*func)(self, name, NULL);
3737 if (res < 0)
3738 return NULL;
3739 Py_INCREF(Py_None);
3740 return Py_None;
3741}
3742
Tim Peters6d6c1a32001-08-02 04:15:00 +00003743static PyObject *
3744wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3745{
3746 hashfunc func = (hashfunc)wrapped;
3747 long res;
3748
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003749 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003750 return NULL;
3751 res = (*func)(self);
3752 if (res == -1 && PyErr_Occurred())
3753 return NULL;
3754 return PyInt_FromLong(res);
3755}
3756
Tim Peters6d6c1a32001-08-02 04:15:00 +00003757static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003758wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003759{
3760 ternaryfunc func = (ternaryfunc)wrapped;
3761
Guido van Rossumc8e56452001-10-22 00:43:43 +00003762 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003763}
3764
Tim Peters6d6c1a32001-08-02 04:15:00 +00003765static PyObject *
3766wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3767{
3768 richcmpfunc func = (richcmpfunc)wrapped;
3769 PyObject *other;
3770
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003771 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003772 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003773 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003774 return (*func)(self, other, op);
3775}
3776
3777#undef RICHCMP_WRAPPER
3778#define RICHCMP_WRAPPER(NAME, OP) \
3779static PyObject * \
3780richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3781{ \
3782 return wrap_richcmpfunc(self, args, wrapped, OP); \
3783}
3784
Jack Jansen8e938b42001-08-08 15:29:49 +00003785RICHCMP_WRAPPER(lt, Py_LT)
3786RICHCMP_WRAPPER(le, Py_LE)
3787RICHCMP_WRAPPER(eq, Py_EQ)
3788RICHCMP_WRAPPER(ne, Py_NE)
3789RICHCMP_WRAPPER(gt, Py_GT)
3790RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791
Tim Peters6d6c1a32001-08-02 04:15:00 +00003792static PyObject *
3793wrap_next(PyObject *self, PyObject *args, void *wrapped)
3794{
3795 unaryfunc func = (unaryfunc)wrapped;
3796 PyObject *res;
3797
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003798 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003799 return NULL;
3800 res = (*func)(self);
3801 if (res == NULL && !PyErr_Occurred())
3802 PyErr_SetNone(PyExc_StopIteration);
3803 return res;
3804}
3805
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806static PyObject *
3807wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3808{
3809 descrgetfunc func = (descrgetfunc)wrapped;
3810 PyObject *obj;
3811 PyObject *type = NULL;
3812
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003813 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00003815 if (obj == Py_None)
3816 obj = NULL;
3817 if (type == Py_None)
3818 type = NULL;
3819 if (type == NULL &&obj == NULL) {
3820 PyErr_SetString(PyExc_TypeError,
3821 "__get__(None, None) is invalid");
3822 return NULL;
3823 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824 return (*func)(self, obj, type);
3825}
3826
Tim Peters6d6c1a32001-08-02 04:15:00 +00003827static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003828wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829{
3830 descrsetfunc func = (descrsetfunc)wrapped;
3831 PyObject *obj, *value;
3832 int ret;
3833
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003834 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003835 return NULL;
3836 ret = (*func)(self, obj, value);
3837 if (ret < 0)
3838 return NULL;
3839 Py_INCREF(Py_None);
3840 return Py_None;
3841}
Guido van Rossum22b13872002-08-06 21:41:44 +00003842
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003843static PyObject *
3844wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3845{
3846 descrsetfunc func = (descrsetfunc)wrapped;
3847 PyObject *obj;
3848 int ret;
3849
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003850 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003851 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003852 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00003853 ret = (*func)(self, obj, NULL);
3854 if (ret < 0)
3855 return NULL;
3856 Py_INCREF(Py_None);
3857 return Py_None;
3858}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003859
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003861wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862{
3863 initproc func = (initproc)wrapped;
3864
Guido van Rossumc8e56452001-10-22 00:43:43 +00003865 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866 return NULL;
3867 Py_INCREF(Py_None);
3868 return Py_None;
3869}
3870
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003872tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003873{
Barry Warsaw60f01882001-08-22 19:24:42 +00003874 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003875 PyObject *arg0, *res;
3876
3877 if (self == NULL || !PyType_Check(self))
3878 Py_FatalError("__new__() called with non-type 'self'");
3879 type = (PyTypeObject *)self;
3880 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003881 PyErr_Format(PyExc_TypeError,
3882 "%s.__new__(): not enough arguments",
3883 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003884 return NULL;
3885 }
3886 arg0 = PyTuple_GET_ITEM(args, 0);
3887 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003888 PyErr_Format(PyExc_TypeError,
3889 "%s.__new__(X): X is not a type object (%s)",
3890 type->tp_name,
3891 arg0->ob_type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003892 return NULL;
3893 }
3894 subtype = (PyTypeObject *)arg0;
3895 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003896 PyErr_Format(PyExc_TypeError,
3897 "%s.__new__(%s): %s is not a subtype of %s",
3898 type->tp_name,
3899 subtype->tp_name,
3900 subtype->tp_name,
3901 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003902 return NULL;
3903 }
Barry Warsaw60f01882001-08-22 19:24:42 +00003904
3905 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00003906 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00003907 most derived base that's not a heap type is this type. */
3908 staticbase = subtype;
3909 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3910 staticbase = staticbase->tp_base;
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003911 /* If staticbase is NULL now, it is a really weird type.
Thomas Wouters89f507f2006-12-13 04:49:30 +00003912 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003913 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00003914 PyErr_Format(PyExc_TypeError,
3915 "%s.__new__(%s) is not safe, use %s.__new__()",
3916 type->tp_name,
3917 subtype->tp_name,
3918 staticbase == NULL ? "?" : staticbase->tp_name);
3919 return NULL;
3920 }
3921
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003922 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3923 if (args == NULL)
3924 return NULL;
3925 res = type->tp_new(subtype, args, kwds);
3926 Py_DECREF(args);
3927 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003928}
3929
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003930static struct PyMethodDef tp_new_methoddef[] = {
3931 {"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00003932 PyDoc_STR("T.__new__(S, ...) -> "
3933 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00003934 {0}
3935};
3936
3937static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003938add_tp_new_wrapper(PyTypeObject *type)
3939{
Guido van Rossumf040ede2001-08-07 16:40:56 +00003940 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003941
Guido van Rossum687ae002001-10-15 22:03:32 +00003942 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00003943 return 0;
3944 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003945 if (func == NULL)
3946 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00003947 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00003948 Py_DECREF(func);
3949 return -1;
3950 }
3951 Py_DECREF(func);
3952 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00003953}
3954
Guido van Rossumf040ede2001-08-07 16:40:56 +00003955/* Slot wrappers that call the corresponding __foo__ slot. See comments
3956 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003957
Guido van Rossumdc91b992001-08-08 22:26:22 +00003958#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003959static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003960FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00003962 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003963 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003964}
3965
Guido van Rossumdc91b992001-08-08 22:26:22 +00003966#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00003968FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00003970 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00003971 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972}
3973
Guido van Rossumcd118802003-01-06 22:57:47 +00003974/* Boolean helper for SLOT1BINFULL().
3975 right.__class__ is a nontrivial subclass of left.__class__. */
3976static int
3977method_is_overloaded(PyObject *left, PyObject *right, char *name)
3978{
3979 PyObject *a, *b;
3980 int ok;
3981
3982 b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3983 if (b == NULL) {
3984 PyErr_Clear();
3985 /* If right doesn't have it, it's not overloaded */
3986 return 0;
3987 }
3988
3989 a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3990 if (a == NULL) {
3991 PyErr_Clear();
3992 Py_DECREF(b);
3993 /* If right has it but left doesn't, it's overloaded */
3994 return 1;
3995 }
3996
3997 ok = PyObject_RichCompareBool(a, b, Py_NE);
3998 Py_DECREF(a);
3999 Py_DECREF(b);
4000 if (ok < 0) {
4001 PyErr_Clear();
4002 return 0;
4003 }
4004
4005 return ok;
4006}
4007
Guido van Rossumdc91b992001-08-08 22:26:22 +00004008
4009#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004010static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004011FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004013 static PyObject *cache_str, *rcache_str; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004014 int do_other = self->ob_type != other->ob_type && \
4015 other->ob_type->tp_as_number != NULL && \
4016 other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004017 if (self->ob_type->tp_as_number != NULL && \
4018 self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
4019 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004020 if (do_other && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004021 PyType_IsSubtype(other->ob_type, self->ob_type) && \
4022 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004023 r = call_maybe( \
4024 other, ROPSTR, &rcache_str, "(O)", self); \
4025 if (r != Py_NotImplemented) \
4026 return r; \
4027 Py_DECREF(r); \
4028 do_other = 0; \
4029 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004030 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004031 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004032 if (r != Py_NotImplemented || \
4033 other->ob_type == self->ob_type) \
4034 return r; \
4035 Py_DECREF(r); \
4036 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004037 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004038 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004039 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004040 } \
4041 Py_INCREF(Py_NotImplemented); \
4042 return Py_NotImplemented; \
4043}
4044
4045#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4046 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4047
4048#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4049static PyObject * \
4050FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4051{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004052 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004053 return call_method(self, OPSTR, &cache_str, \
4054 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004055}
4056
Martin v. Löwis18e16552006-02-15 17:27:45 +00004057static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004058slot_sq_length(PyObject *self)
4059{
Guido van Rossum2730b132001-08-28 18:22:14 +00004060 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004061 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004062 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004063
4064 if (res == NULL)
4065 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004066 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004067 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004068 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004069 if (!PyErr_Occurred())
4070 PyErr_SetString(PyExc_ValueError,
4071 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004072 return -1;
4073 }
Guido van Rossum26111622001-10-01 16:42:49 +00004074 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004075}
4076
Guido van Rossumf4593e02001-10-03 12:09:30 +00004077/* Super-optimized version of slot_sq_item.
4078 Other slots could do the same... */
4079static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004080slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004081{
4082 static PyObject *getitem_str;
4083 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4084 descrgetfunc f;
4085
4086 if (getitem_str == NULL) {
4087 getitem_str = PyString_InternFromString("__getitem__");
4088 if (getitem_str == NULL)
4089 return NULL;
4090 }
4091 func = _PyType_Lookup(self->ob_type, getitem_str);
4092 if (func != NULL) {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004093 if ((f = func->ob_type->tp_descr_get) == NULL)
4094 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004095 else {
Guido van Rossumf4593e02001-10-03 12:09:30 +00004096 func = f(func, self, (PyObject *)(self->ob_type));
Neal Norwitz673cd822002-10-18 16:33:13 +00004097 if (func == NULL) {
4098 return NULL;
4099 }
4100 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004101 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004102 if (ival != NULL) {
4103 args = PyTuple_New(1);
4104 if (args != NULL) {
4105 PyTuple_SET_ITEM(args, 0, ival);
4106 retval = PyObject_Call(func, args, NULL);
4107 Py_XDECREF(args);
4108 Py_XDECREF(func);
4109 return retval;
4110 }
4111 }
4112 }
4113 else {
4114 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4115 }
4116 Py_XDECREF(args);
4117 Py_XDECREF(ival);
4118 Py_XDECREF(func);
4119 return NULL;
4120}
4121
Martin v. Löwis18e16552006-02-15 17:27:45 +00004122SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123
4124static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004125slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126{
4127 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004128 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004129
4130 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004131 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004132 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004133 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004134 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004135 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004136 if (res == NULL)
4137 return -1;
4138 Py_DECREF(res);
4139 return 0;
4140}
4141
4142static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004143slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004144{
4145 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004146 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004147
4148 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004149 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004150 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004151 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004152 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004153 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004154 if (res == NULL)
4155 return -1;
4156 Py_DECREF(res);
4157 return 0;
4158}
4159
4160static int
4161slot_sq_contains(PyObject *self, PyObject *value)
4162{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004163 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004164 int result = -1;
4165
Guido van Rossum60718732001-08-28 17:47:51 +00004166 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004167
Guido van Rossum55f20992001-10-01 17:18:22 +00004168 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004169 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004170 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004171 if (args == NULL)
4172 res = NULL;
4173 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004174 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004175 Py_DECREF(args);
4176 }
4177 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004178 if (res != NULL) {
4179 result = PyObject_IsTrue(res);
4180 Py_DECREF(res);
4181 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004182 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004183 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004184 /* Possible results: -1 and 1 */
4185 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004186 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004187 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004188 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004189}
4190
Tim Peters6d6c1a32001-08-02 04:15:00 +00004191#define slot_mp_length slot_sq_length
4192
Guido van Rossumdc91b992001-08-08 22:26:22 +00004193SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004194
4195static int
4196slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4197{
4198 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004199 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004200
4201 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004202 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004203 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004204 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004205 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004206 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004207 if (res == NULL)
4208 return -1;
4209 Py_DECREF(res);
4210 return 0;
4211}
4212
Guido van Rossumdc91b992001-08-08 22:26:22 +00004213SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4214SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4215SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004216SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4217SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4218
Jeremy Hylton938ace62002-07-17 16:30:39 +00004219static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004220
4221SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4222 nb_power, "__pow__", "__rpow__")
4223
4224static PyObject *
4225slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4226{
Guido van Rossum2730b132001-08-28 18:22:14 +00004227 static PyObject *pow_str;
4228
Guido van Rossumdc91b992001-08-08 22:26:22 +00004229 if (modulus == Py_None)
4230 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004231 /* Three-arg power doesn't use __rpow__. But ternary_op
4232 can call this when the second argument's type uses
4233 slot_nb_power, so check before calling self.__pow__. */
4234 if (self->ob_type->tp_as_number != NULL &&
4235 self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4236 return call_method(self, "__pow__", &pow_str,
4237 "(OO)", other, modulus);
4238 }
4239 Py_INCREF(Py_NotImplemented);
4240 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004241}
4242
4243SLOT0(slot_nb_negative, "__neg__")
4244SLOT0(slot_nb_positive, "__pos__")
4245SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004246
4247static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004248slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004249{
Tim Petersea7f75d2002-12-07 21:39:16 +00004250 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004251 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004252 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004253 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254
Jack Diederich4dafcc42006-11-28 19:15:13 +00004255 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004256 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004257 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004258 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004259 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004260 if (func == NULL)
4261 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004262 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004263 }
4264 args = PyTuple_New(0);
4265 if (args != NULL) {
4266 PyObject *temp = PyObject_Call(func, args, NULL);
4267 Py_DECREF(args);
4268 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004269 if (from_len) {
4270 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004271 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004272 }
4273 else if (PyBool_Check(temp)) {
4274 result = PyObject_IsTrue(temp);
4275 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004276 else {
4277 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004278 "__bool__ should return "
4279 "bool, returned %s",
4280 temp->ob_type->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004281 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004282 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004283 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004284 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004285 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004286 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004287 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004288}
4289
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004290
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004291static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004292slot_nb_index(PyObject *self)
4293{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004294 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004295 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004296}
4297
4298
Guido van Rossumdc91b992001-08-08 22:26:22 +00004299SLOT0(slot_nb_invert, "__invert__")
4300SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4301SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4302SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4303SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4304SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004305
Guido van Rossumdc91b992001-08-08 22:26:22 +00004306SLOT0(slot_nb_int, "__int__")
4307SLOT0(slot_nb_long, "__long__")
4308SLOT0(slot_nb_float, "__float__")
4309SLOT0(slot_nb_oct, "__oct__")
4310SLOT0(slot_nb_hex, "__hex__")
4311SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4312SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4313SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004314SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004315/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4316static PyObject *
4317slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4318{
4319 static PyObject *cache_str;
4320 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4321}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004322SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4323SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4324SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4325SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4326SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4327SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4328 "__floordiv__", "__rfloordiv__")
4329SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4330SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4331SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332
4333static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004334half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004336 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004337 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004338 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339
Guido van Rossum60718732001-08-28 17:47:51 +00004340 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004341 if (func == NULL) {
4342 PyErr_Clear();
4343 }
4344 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004345 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004346 if (args == NULL)
4347 res = NULL;
4348 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004349 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004350 Py_DECREF(args);
4351 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004352 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004353 if (res != Py_NotImplemented) {
4354 if (res == NULL)
4355 return -2;
4356 c = PyInt_AsLong(res);
4357 Py_DECREF(res);
4358 if (c == -1 && PyErr_Occurred())
4359 return -2;
4360 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4361 }
4362 Py_DECREF(res);
4363 }
4364 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004365}
4366
Guido van Rossumab3b0342001-09-18 20:38:53 +00004367/* This slot is published for the benefit of try_3way_compare in object.c */
4368int
4369_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004370{
4371 int c;
4372
Guido van Rossumab3b0342001-09-18 20:38:53 +00004373 if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004374 c = half_compare(self, other);
4375 if (c <= 1)
4376 return c;
4377 }
Guido van Rossumab3b0342001-09-18 20:38:53 +00004378 if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004379 c = half_compare(other, self);
4380 if (c < -1)
4381 return -2;
4382 if (c <= 1)
4383 return -c;
4384 }
4385 return (void *)self < (void *)other ? -1 :
4386 (void *)self > (void *)other ? 1 : 0;
4387}
4388
4389static PyObject *
4390slot_tp_repr(PyObject *self)
4391{
4392 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004393 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004394
Guido van Rossum60718732001-08-28 17:47:51 +00004395 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004396 if (func != NULL) {
4397 res = PyEval_CallObject(func, NULL);
4398 Py_DECREF(func);
4399 return res;
4400 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004401 PyErr_Clear();
4402 return PyString_FromFormat("<%s object at %p>",
4403 self->ob_type->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004404}
4405
4406static PyObject *
4407slot_tp_str(PyObject *self)
4408{
4409 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004410 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004411
Guido van Rossum60718732001-08-28 17:47:51 +00004412 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004413 if (func != NULL) {
4414 res = PyEval_CallObject(func, NULL);
4415 Py_DECREF(func);
4416 return res;
4417 }
4418 else {
4419 PyErr_Clear();
4420 return slot_tp_repr(self);
4421 }
4422}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004423
4424static long
4425slot_tp_hash(PyObject *self)
4426{
Guido van Rossum4011a242006-08-17 23:09:57 +00004427 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004428 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004429 long h;
4430
Guido van Rossum60718732001-08-28 17:47:51 +00004431 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004432
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004433 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004434 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004435 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004436 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004437
4438 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004439 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
4440 self->ob_type->tp_name);
4441 return -1;
4442 }
4443
Guido van Rossum4011a242006-08-17 23:09:57 +00004444 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004445 Py_DECREF(func);
4446 if (res == NULL)
4447 return -1;
4448 if (PyLong_Check(res))
4449 h = PyLong_Type.tp_hash(res);
4450 else
4451 h = PyInt_AsLong(res);
4452 Py_DECREF(res);
4453 if (h == -1 && !PyErr_Occurred())
4454 h = -2;
4455 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004456}
4457
4458static PyObject *
4459slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4460{
Guido van Rossum60718732001-08-28 17:47:51 +00004461 static PyObject *call_str;
4462 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004463 PyObject *res;
4464
4465 if (meth == NULL)
4466 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004467
4468 /* PyObject_Call() will end up calling slot_tp_call() again if
4469 the object returned for __call__ has __call__ itself defined
4470 upon it. This can be an infinite recursion if you set
4471 __call__ in a class to an instance of it. */
4472 if (Py_EnterRecursiveCall(" in __call__")) {
4473 Py_DECREF(meth);
4474 return NULL;
4475 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004476 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004477 Py_LeaveRecursiveCall();
4478
Tim Peters6d6c1a32001-08-02 04:15:00 +00004479 Py_DECREF(meth);
4480 return res;
4481}
4482
Guido van Rossum14a6f832001-10-17 13:59:09 +00004483/* There are two slot dispatch functions for tp_getattro.
4484
4485 - slot_tp_getattro() is used when __getattribute__ is overridden
4486 but no __getattr__ hook is present;
4487
4488 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4489
Guido van Rossumc334df52002-04-04 23:44:47 +00004490 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4491 detects the absence of __getattr__ and then installs the simpler slot if
4492 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004493
Tim Peters6d6c1a32001-08-02 04:15:00 +00004494static PyObject *
4495slot_tp_getattro(PyObject *self, PyObject *name)
4496{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004497 static PyObject *getattribute_str = NULL;
4498 return call_method(self, "__getattribute__", &getattribute_str,
4499 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004500}
4501
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004502static PyObject *
4503slot_tp_getattr_hook(PyObject *self, PyObject *name)
4504{
4505 PyTypeObject *tp = self->ob_type;
4506 PyObject *getattr, *getattribute, *res;
4507 static PyObject *getattribute_str = NULL;
4508 static PyObject *getattr_str = NULL;
4509
4510 if (getattr_str == NULL) {
4511 getattr_str = PyString_InternFromString("__getattr__");
4512 if (getattr_str == NULL)
4513 return NULL;
4514 }
4515 if (getattribute_str == NULL) {
4516 getattribute_str =
4517 PyString_InternFromString("__getattribute__");
4518 if (getattribute_str == NULL)
4519 return NULL;
4520 }
4521 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004522 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004523 /* No __getattr__ hook: use a simpler dispatcher */
4524 tp->tp_getattro = slot_tp_getattro;
4525 return slot_tp_getattro(self, name);
4526 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004527 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004528 if (getattribute == NULL ||
4529 (getattribute->ob_type == &PyWrapperDescr_Type &&
4530 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4531 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004532 res = PyObject_GenericGetAttr(self, name);
4533 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004534 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004535 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004536 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004537 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004538 }
4539 return res;
4540}
4541
Tim Peters6d6c1a32001-08-02 04:15:00 +00004542static int
4543slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4544{
4545 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004546 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004547
4548 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004549 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004550 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004551 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004552 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004553 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004554 if (res == NULL)
4555 return -1;
4556 Py_DECREF(res);
4557 return 0;
4558}
4559
Tim Peters6d6c1a32001-08-02 04:15:00 +00004560static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004561half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004562{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004563 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004564 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004565
Guido van Rossum60718732001-08-28 17:47:51 +00004566 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004567 if (func == NULL) {
4568 PyErr_Clear();
4569 Py_INCREF(Py_NotImplemented);
4570 return Py_NotImplemented;
4571 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004572 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004573 if (args == NULL)
4574 res = NULL;
4575 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004576 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004577 Py_DECREF(args);
4578 }
4579 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004580 return res;
4581}
4582
Guido van Rossumb8f63662001-08-15 23:57:02 +00004583static PyObject *
4584slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4585{
4586 PyObject *res;
4587
4588 if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4589 res = half_richcompare(self, other, op);
4590 if (res != Py_NotImplemented)
4591 return res;
4592 Py_DECREF(res);
4593 }
4594 if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004595 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004596 if (res != Py_NotImplemented) {
4597 return res;
4598 }
4599 Py_DECREF(res);
4600 }
4601 Py_INCREF(Py_NotImplemented);
4602 return Py_NotImplemented;
4603}
4604
4605static PyObject *
4606slot_tp_iter(PyObject *self)
4607{
4608 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004609 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004610
Guido van Rossum60718732001-08-28 17:47:51 +00004611 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004612 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004613 PyObject *args;
4614 args = res = PyTuple_New(0);
4615 if (args != NULL) {
4616 res = PyObject_Call(func, args, NULL);
4617 Py_DECREF(args);
4618 }
4619 Py_DECREF(func);
4620 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004621 }
4622 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004623 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004624 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004625 PyErr_Format(PyExc_TypeError,
4626 "'%.200s' object is not iterable",
4627 self->ob_type->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004628 return NULL;
4629 }
4630 Py_DECREF(func);
4631 return PySeqIter_New(self);
4632}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004633
4634static PyObject *
4635slot_tp_iternext(PyObject *self)
4636{
Guido van Rossum2730b132001-08-28 18:22:14 +00004637 static PyObject *next_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004638 return call_method(self, "next", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639}
4640
Guido van Rossum1a493502001-08-17 16:47:50 +00004641static PyObject *
4642slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4643{
4644 PyTypeObject *tp = self->ob_type;
4645 PyObject *get;
4646 static PyObject *get_str = NULL;
4647
4648 if (get_str == NULL) {
4649 get_str = PyString_InternFromString("__get__");
4650 if (get_str == NULL)
4651 return NULL;
4652 }
4653 get = _PyType_Lookup(tp, get_str);
4654 if (get == NULL) {
4655 /* Avoid further slowdowns */
4656 if (tp->tp_descr_get == slot_tp_descr_get)
4657 tp->tp_descr_get = NULL;
4658 Py_INCREF(self);
4659 return self;
4660 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004661 if (obj == NULL)
4662 obj = Py_None;
4663 if (type == NULL)
4664 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004665 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004666}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004667
4668static int
4669slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4670{
Guido van Rossum2c252392001-08-24 10:13:31 +00004671 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004672 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004673
4674 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004675 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004676 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004677 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004678 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004679 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004680 if (res == NULL)
4681 return -1;
4682 Py_DECREF(res);
4683 return 0;
4684}
4685
4686static int
4687slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4688{
Guido van Rossum60718732001-08-28 17:47:51 +00004689 static PyObject *init_str;
4690 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004691 PyObject *res;
4692
4693 if (meth == NULL)
4694 return -1;
4695 res = PyObject_Call(meth, args, kwds);
4696 Py_DECREF(meth);
4697 if (res == NULL)
4698 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004699 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004700 PyErr_Format(PyExc_TypeError,
4701 "__init__() should return None, not '%.200s'",
4702 res->ob_type->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004703 Py_DECREF(res);
4704 return -1;
4705 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004706 Py_DECREF(res);
4707 return 0;
4708}
4709
4710static PyObject *
4711slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4712{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004713 static PyObject *new_str;
4714 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004715 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004716 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717
Guido van Rossum7bed2132002-08-08 21:57:53 +00004718 if (new_str == NULL) {
4719 new_str = PyString_InternFromString("__new__");
4720 if (new_str == NULL)
4721 return NULL;
4722 }
4723 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724 if (func == NULL)
4725 return NULL;
4726 assert(PyTuple_Check(args));
4727 n = PyTuple_GET_SIZE(args);
4728 newargs = PyTuple_New(n+1);
4729 if (newargs == NULL)
4730 return NULL;
4731 Py_INCREF(type);
4732 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4733 for (i = 0; i < n; i++) {
4734 x = PyTuple_GET_ITEM(args, i);
4735 Py_INCREF(x);
4736 PyTuple_SET_ITEM(newargs, i+1, x);
4737 }
4738 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004739 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004740 Py_DECREF(func);
4741 return x;
4742}
4743
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004744static void
4745slot_tp_del(PyObject *self)
4746{
4747 static PyObject *del_str = NULL;
4748 PyObject *del, *res;
4749 PyObject *error_type, *error_value, *error_traceback;
4750
4751 /* Temporarily resurrect the object. */
4752 assert(self->ob_refcnt == 0);
4753 self->ob_refcnt = 1;
4754
4755 /* Save the current exception, if any. */
4756 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4757
4758 /* Execute __del__ method, if any. */
4759 del = lookup_maybe(self, "__del__", &del_str);
4760 if (del != NULL) {
4761 res = PyEval_CallObject(del, NULL);
4762 if (res == NULL)
4763 PyErr_WriteUnraisable(del);
4764 else
4765 Py_DECREF(res);
4766 Py_DECREF(del);
4767 }
4768
4769 /* Restore the saved exception. */
4770 PyErr_Restore(error_type, error_value, error_traceback);
4771
4772 /* Undo the temporary resurrection; can't use DECREF here, it would
4773 * cause a recursive call.
4774 */
4775 assert(self->ob_refcnt > 0);
4776 if (--self->ob_refcnt == 0)
4777 return; /* this is the normal path out */
4778
4779 /* __del__ resurrected it! Make it look like the original Py_DECREF
4780 * never happened.
4781 */
4782 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004783 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004784 _Py_NewReference(self);
4785 self->ob_refcnt = refcnt;
4786 }
4787 assert(!PyType_IS_GC(self->ob_type) ||
4788 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004789 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
4790 * we need to undo that. */
4791 _Py_DEC_REFTOTAL;
4792 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4793 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004794 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4795 * _Py_NewReference bumped tp_allocs: both of those need to be
4796 * undone.
4797 */
4798#ifdef COUNT_ALLOCS
4799 --self->ob_type->tp_frees;
4800 --self->ob_type->tp_allocs;
4801#endif
4802}
4803
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004804
4805/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00004806 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00004807 structure, which incorporates the additional structures used for numbers,
4808 sequences and mappings.
4809 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004810 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00004811 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4812 terminated with an all-zero entry. (This table is further initialized and
4813 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004814
Guido van Rossum6d204072001-10-21 00:44:31 +00004815typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004816
4817#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00004818#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004819#undef ETSLOT
4820#undef SQSLOT
4821#undef MPSLOT
4822#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00004823#undef UNSLOT
4824#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004825#undef BINSLOT
4826#undef RBINSLOT
4827
Guido van Rossum6d204072001-10-21 00:44:31 +00004828#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004829 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4830 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00004831#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4832 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004833 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00004834#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00004835 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00004836 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00004837#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4838 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4839#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4840 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4841#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4842 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4843#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4844 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4845 "x." NAME "() <==> " DOC)
4846#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4847 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4848 "x." NAME "(y) <==> x" DOC "y")
4849#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4850 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4851 "x." NAME "(y) <==> x" DOC "y")
4852#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4853 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4854 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00004855#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4856 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4857 "x." NAME "(y) <==> " DOC)
4858#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
4859 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4860 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004861
4862static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00004863 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00004864 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00004865 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
4866 The logic in abstract.c always falls back to nb_add/nb_multiply in
4867 this case. Defining both the nb_* and the sq_* slots to call the
4868 user-defined methods has unexpected side-effects, as shown by
4869 test_descr.notimplemented() */
4870 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
4871 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004872 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00004873 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004874 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Armin Rigofd163f92005-12-29 15:59:19 +00004875 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004876 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4877 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00004878 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00004879 "x.__getslice__(i, j) <==> x[i:j]\n\
4880 \n\
4881 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004882 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004883 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004884 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00004885 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004886 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00004887 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00004888 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
4889 \n\
4890 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004891 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00004892 "x.__delslice__(i, j) <==> del x[i:j]\n\
4893 \n\
4894 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00004895 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4896 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00004897 SQSLOT("__iadd__", sq_inplace_concat, NULL,
4898 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
4899 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004900 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004901
Martin v. Löwis18e16552006-02-15 17:27:45 +00004902 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00004903 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00004904 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004905 wrap_binaryfunc,
4906 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004907 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004908 wrap_objobjargproc,
4909 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004910 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00004911 wrap_delitem,
4912 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004913
Guido van Rossum6d204072001-10-21 00:44:31 +00004914 BINSLOT("__add__", nb_add, slot_nb_add,
4915 "+"),
4916 RBINSLOT("__radd__", nb_add, slot_nb_add,
4917 "+"),
4918 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4919 "-"),
4920 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4921 "-"),
4922 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4923 "*"),
4924 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4925 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004926 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4927 "%"),
4928 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4929 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00004930 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00004931 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00004932 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00004933 "divmod(y, x)"),
4934 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4935 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4936 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4937 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4938 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4939 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4940 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4941 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00004942 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00004943 "x != 0"),
4944 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4945 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4946 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4947 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4948 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4949 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4950 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4951 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4952 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4953 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4954 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004955 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4956 "int(x)"),
4957 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4958 "long(x)"),
4959 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4960 "float(x)"),
4961 UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4962 "oct(x)"),
4963 UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4964 "hex(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004965 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004966 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004967 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4968 wrap_binaryfunc, "+"),
4969 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4970 wrap_binaryfunc, "-"),
4971 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4972 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004973 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4974 wrap_binaryfunc, "%"),
4975 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00004976 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00004977 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4978 wrap_binaryfunc, "<<"),
4979 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4980 wrap_binaryfunc, ">>"),
4981 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4982 wrap_binaryfunc, "&"),
4983 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4984 wrap_binaryfunc, "^"),
4985 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4986 wrap_binaryfunc, "|"),
4987 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4988 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4989 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4990 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4991 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4992 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4993 IBSLOT("__itruediv__", nb_inplace_true_divide,
4994 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004995
Guido van Rossum6d204072001-10-21 00:44:31 +00004996 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4997 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00004998 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00004999 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5000 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005001 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005002 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5003 "x.__cmp__(y) <==> cmp(x,y)"),
5004 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5005 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005006 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5007 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005008 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005009 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5010 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5011 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5012 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5013 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5014 "x.__setattr__('name', value) <==> x.name = value"),
5015 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5016 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5017 "x.__delattr__('name') <==> del x.name"),
5018 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5019 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5020 "x.__lt__(y) <==> x<y"),
5021 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5022 "x.__le__(y) <==> x<=y"),
5023 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5024 "x.__eq__(y) <==> x==y"),
5025 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5026 "x.__ne__(y) <==> x!=y"),
5027 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5028 "x.__gt__(y) <==> x>y"),
5029 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5030 "x.__ge__(y) <==> x>=y"),
5031 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5032 "x.__iter__() <==> iter(x)"),
5033 TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
5034 "x.next() -> the next value, or raise StopIteration"),
5035 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5036 "descr.__get__(obj[, type]) -> value"),
5037 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5038 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005039 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5040 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005041 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005042 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005043 "see x.__class__.__doc__ for signature",
5044 PyWrapperFlag_KEYWORDS),
5045 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005046 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005047 {NULL}
5048};
5049
Guido van Rossumc334df52002-04-04 23:44:47 +00005050/* Given a type pointer and an offset gotten from a slotdef entry, return a
5051 pointer to the actual slot. This is not quite the same as simply adding
5052 the offset to the type pointer, since it takes care to indirect through the
5053 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5054 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005055static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005056slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005057{
5058 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005059 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005060
Guido van Rossume5c691a2003-03-07 15:13:17 +00005061 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005062 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005063 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5064 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5065 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005066 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005067 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005068 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5069 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005070 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005071 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005072 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5073 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005074 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005075 }
5076 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005077 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005078 }
5079 if (ptr != NULL)
5080 ptr += offset;
5081 return (void **)ptr;
5082}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005083
Guido van Rossumc334df52002-04-04 23:44:47 +00005084/* Length of array of slotdef pointers used to store slots with the
5085 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5086 the same __name__, for any __name__. Since that's a static property, it is
5087 appropriate to declare fixed-size arrays for this. */
5088#define MAX_EQUIV 10
5089
5090/* Return a slot pointer for a given name, but ONLY if the attribute has
5091 exactly one slot function. The name must be an interned string. */
5092static void **
5093resolve_slotdups(PyTypeObject *type, PyObject *name)
5094{
5095 /* XXX Maybe this could be optimized more -- but is it worth it? */
5096
5097 /* pname and ptrs act as a little cache */
5098 static PyObject *pname;
5099 static slotdef *ptrs[MAX_EQUIV];
5100 slotdef *p, **pp;
5101 void **res, **ptr;
5102
5103 if (pname != name) {
5104 /* Collect all slotdefs that match name into ptrs. */
5105 pname = name;
5106 pp = ptrs;
5107 for (p = slotdefs; p->name_strobj; p++) {
5108 if (p->name_strobj == name)
5109 *pp++ = p;
5110 }
5111 *pp = NULL;
5112 }
5113
5114 /* Look in all matching slots of the type; if exactly one of these has
5115 a filled-in slot, return its value. Otherwise return NULL. */
5116 res = NULL;
5117 for (pp = ptrs; *pp; pp++) {
5118 ptr = slotptr(type, (*pp)->offset);
5119 if (ptr == NULL || *ptr == NULL)
5120 continue;
5121 if (res != NULL)
5122 return NULL;
5123 res = ptr;
5124 }
5125 return res;
5126}
5127
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005128/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005129 does some incredibly complex thinking and then sticks something into the
5130 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5131 interests, and then stores a generic wrapper or a specific function into
5132 the slot.) Return a pointer to the next slotdef with a different offset,
5133 because that's convenient for fixup_slot_dispatchers(). */
5134static slotdef *
5135update_one_slot(PyTypeObject *type, slotdef *p)
5136{
5137 PyObject *descr;
5138 PyWrapperDescrObject *d;
5139 void *generic = NULL, *specific = NULL;
5140 int use_generic = 0;
5141 int offset = p->offset;
5142 void **ptr = slotptr(type, offset);
5143
5144 if (ptr == NULL) {
5145 do {
5146 ++p;
5147 } while (p->offset == offset);
5148 return p;
5149 }
5150 do {
5151 descr = _PyType_Lookup(type, p->name_strobj);
5152 if (descr == NULL)
5153 continue;
5154 if (descr->ob_type == &PyWrapperDescr_Type) {
5155 void **tptr = resolve_slotdups(type, p->name_strobj);
5156 if (tptr == NULL || tptr == ptr)
5157 generic = p->function;
5158 d = (PyWrapperDescrObject *)descr;
5159 if (d->d_base->wrapper == p->wrapper &&
5160 PyType_IsSubtype(type, d->d_type))
5161 {
5162 if (specific == NULL ||
5163 specific == d->d_wrapped)
5164 specific = d->d_wrapped;
5165 else
5166 use_generic = 1;
5167 }
5168 }
Guido van Rossum721f62e2002-08-09 02:14:34 +00005169 else if (descr->ob_type == &PyCFunction_Type &&
5170 PyCFunction_GET_FUNCTION(descr) ==
5171 (PyCFunction)tp_new_wrapper &&
5172 strcmp(p->name, "__new__") == 0)
5173 {
5174 /* The __new__ wrapper is not a wrapper descriptor,
5175 so must be special-cased differently.
5176 If we don't do this, creating an instance will
5177 always use slot_tp_new which will look up
5178 __new__ in the MRO which will call tp_new_wrapper
5179 which will look through the base classes looking
5180 for a static base and call its tp_new (usually
5181 PyType_GenericNew), after performing various
5182 sanity checks and constructing a new argument
5183 list. Cut all that nonsense short -- this speeds
5184 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005185 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005186 /* XXX I'm not 100% sure that there isn't a hole
5187 in this reasoning that requires additional
5188 sanity checks. I'll buy the first person to
5189 point out a bug in this reasoning a beer. */
5190 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005191 else {
5192 use_generic = 1;
5193 generic = p->function;
5194 }
5195 } while ((++p)->offset == offset);
5196 if (specific && !use_generic)
5197 *ptr = specific;
5198 else
5199 *ptr = generic;
5200 return p;
5201}
5202
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005203/* In the type, update the slots whose slotdefs are gathered in the pp array.
5204 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005205static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005206update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005207{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005208 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005209
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005210 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005211 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005212 return 0;
5213}
5214
Guido van Rossumc334df52002-04-04 23:44:47 +00005215/* Comparison function for qsort() to compare slotdefs by their offset, and
5216 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005217static int
5218slotdef_cmp(const void *aa, const void *bb)
5219{
5220 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5221 int c = a->offset - b->offset;
5222 if (c != 0)
5223 return c;
5224 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005225 /* Cannot use a-b, as this gives off_t,
5226 which may lose precision when converted to int. */
5227 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005228}
5229
Guido van Rossumc334df52002-04-04 23:44:47 +00005230/* Initialize the slotdefs table by adding interned string objects for the
5231 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005232static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005233init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005234{
5235 slotdef *p;
5236 static int initialized = 0;
5237
5238 if (initialized)
5239 return;
5240 for (p = slotdefs; p->name; p++) {
5241 p->name_strobj = PyString_InternFromString(p->name);
5242 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005243 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005244 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005245 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5246 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005247 initialized = 1;
5248}
5249
Guido van Rossumc334df52002-04-04 23:44:47 +00005250/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005251static int
5252update_slot(PyTypeObject *type, PyObject *name)
5253{
Guido van Rossumc334df52002-04-04 23:44:47 +00005254 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005255 slotdef *p;
5256 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005257 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005258
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005259 init_slotdefs();
5260 pp = ptrs;
5261 for (p = slotdefs; p->name; p++) {
5262 /* XXX assume name is interned! */
5263 if (p->name_strobj == name)
5264 *pp++ = p;
5265 }
5266 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005267 for (pp = ptrs; *pp; pp++) {
5268 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005269 offset = p->offset;
5270 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005271 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005272 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005273 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005274 if (ptrs[0] == NULL)
5275 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005276 return update_subclasses(type, name,
5277 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005278}
5279
Guido van Rossumc334df52002-04-04 23:44:47 +00005280/* Store the proper functions in the slot dispatches at class (type)
5281 definition time, based upon which operations the class overrides in its
5282 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005283static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005284fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005285{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005286 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005287
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005288 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005289 for (p = slotdefs; p->name; )
5290 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005291}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005292
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005293static void
5294update_all_slots(PyTypeObject* type)
5295{
5296 slotdef *p;
5297
5298 init_slotdefs();
5299 for (p = slotdefs; p->name; p++) {
5300 /* update_slot returns int but can't actually fail */
5301 update_slot(type, p->name_strobj);
5302 }
5303}
5304
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005305/* recurse_down_subclasses() and update_subclasses() are mutually
5306 recursive functions to call a callback for all subclasses,
5307 but refraining from recursing into subclasses that define 'name'. */
5308
5309static int
5310update_subclasses(PyTypeObject *type, PyObject *name,
5311 update_callback callback, void *data)
5312{
5313 if (callback(type, data) < 0)
5314 return -1;
5315 return recurse_down_subclasses(type, name, callback, data);
5316}
5317
5318static int
5319recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5320 update_callback callback, void *data)
5321{
5322 PyTypeObject *subclass;
5323 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005324 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005325
5326 subclasses = type->tp_subclasses;
5327 if (subclasses == NULL)
5328 return 0;
5329 assert(PyList_Check(subclasses));
5330 n = PyList_GET_SIZE(subclasses);
5331 for (i = 0; i < n; i++) {
5332 ref = PyList_GET_ITEM(subclasses, i);
5333 assert(PyWeakref_CheckRef(ref));
5334 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5335 assert(subclass != NULL);
5336 if ((PyObject *)subclass == Py_None)
5337 continue;
5338 assert(PyType_Check(subclass));
5339 /* Avoid recursing down into unaffected classes */
5340 dict = subclass->tp_dict;
5341 if (dict != NULL && PyDict_Check(dict) &&
5342 PyDict_GetItem(dict, name) != NULL)
5343 continue;
5344 if (update_subclasses(subclass, name, callback, data) < 0)
5345 return -1;
5346 }
5347 return 0;
5348}
5349
Guido van Rossum6d204072001-10-21 00:44:31 +00005350/* This function is called by PyType_Ready() to populate the type's
5351 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005352 function slot (like tp_repr) that's defined in the type, one or more
5353 corresponding descriptors are added in the type's tp_dict dictionary
5354 under the appropriate name (like __repr__). Some function slots
5355 cause more than one descriptor to be added (for example, the nb_add
5356 slot adds both __add__ and __radd__ descriptors) and some function
5357 slots compete for the same descriptor (for example both sq_item and
5358 mp_subscript generate a __getitem__ descriptor).
5359
5360 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005361 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005362 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005363 between competing slots: the members of PyHeapTypeObject are listed
5364 from most general to least general, so the most general slot is
5365 preferred. In particular, because as_mapping comes before as_sequence,
5366 for a type that defines both mp_subscript and sq_item, mp_subscript
5367 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005368
5369 This only adds new descriptors and doesn't overwrite entries in
5370 tp_dict that were previously defined. The descriptors contain a
5371 reference to the C function they must call, so that it's safe if they
5372 are copied into a subtype's __dict__ and the subtype has a different
5373 C function in its slot -- calling the method defined by the
5374 descriptor will call the C function that was used to create it,
5375 rather than the C function present in the slot when it is called.
5376 (This is important because a subtype may have a C function in the
5377 slot that calls the method from the dictionary, and we want to avoid
5378 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005379
5380static int
5381add_operators(PyTypeObject *type)
5382{
5383 PyObject *dict = type->tp_dict;
5384 slotdef *p;
5385 PyObject *descr;
5386 void **ptr;
5387
5388 init_slotdefs();
5389 for (p = slotdefs; p->name; p++) {
5390 if (p->wrapper == NULL)
5391 continue;
5392 ptr = slotptr(type, p->offset);
5393 if (!ptr || !*ptr)
5394 continue;
5395 if (PyDict_GetItem(dict, p->name_strobj))
5396 continue;
5397 descr = PyDescr_NewWrapper(type, p, *ptr);
5398 if (descr == NULL)
5399 return -1;
5400 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5401 return -1;
5402 Py_DECREF(descr);
5403 }
5404 if (type->tp_new != NULL) {
5405 if (add_tp_new_wrapper(type) < 0)
5406 return -1;
5407 }
5408 return 0;
5409}
5410
Guido van Rossum705f0f52001-08-24 16:47:00 +00005411
5412/* Cooperative 'super' */
5413
5414typedef struct {
5415 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005416 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005417 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005418 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005419} superobject;
5420
Guido van Rossum6f799372001-09-20 20:46:19 +00005421static PyMemberDef super_members[] = {
5422 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5423 "the class invoking super()"},
5424 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5425 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005426 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005427 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005428 {0}
5429};
5430
Guido van Rossum705f0f52001-08-24 16:47:00 +00005431static void
5432super_dealloc(PyObject *self)
5433{
5434 superobject *su = (superobject *)self;
5435
Guido van Rossum048eb752001-10-02 21:24:57 +00005436 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005437 Py_XDECREF(su->obj);
5438 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005439 Py_XDECREF(su->obj_type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005440 self->ob_type->tp_free(self);
5441}
5442
5443static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005444super_repr(PyObject *self)
5445{
5446 superobject *su = (superobject *)self;
5447
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005448 if (su->obj_type)
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005449 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005450 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005451 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005452 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005453 else
5454 return PyString_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005455 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005456 su->type ? su->type->tp_name : "NULL");
5457}
5458
5459static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005460super_getattro(PyObject *self, PyObject *name)
5461{
5462 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005463 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005464
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005465 if (!skip) {
5466 /* We want __class__ to return the class of the super object
5467 (i.e. super, or a subclass), not the class of su->obj. */
5468 skip = (PyString_Check(name) &&
5469 PyString_GET_SIZE(name) == 9 &&
5470 strcmp(PyString_AS_STRING(name), "__class__") == 0);
5471 }
5472
5473 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005474 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005475 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005476 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005477 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005478
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005479 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005480 mro = starttype->tp_mro;
5481
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005482 if (mro == NULL)
5483 n = 0;
5484 else {
5485 assert(PyTuple_Check(mro));
5486 n = PyTuple_GET_SIZE(mro);
5487 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005488 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005489 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005490 break;
5491 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005492 i++;
5493 res = NULL;
5494 for (; i < n; i++) {
5495 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005496 if (PyType_Check(tmp))
5497 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005498 else
5499 continue;
5500 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005501 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005502 Py_INCREF(res);
5503 f = res->ob_type->tp_descr_get;
5504 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005505 tmp = f(res,
5506 /* Only pass 'obj' param if
5507 this is instance-mode super
5508 (See SF ID #743627)
5509 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005510 (su->obj == (PyObject *)
5511 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005512 ? (PyObject *)NULL
5513 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005514 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005515 Py_DECREF(res);
5516 res = tmp;
5517 }
5518 return res;
5519 }
5520 }
5521 }
5522 return PyObject_GenericGetAttr(self, name);
5523}
5524
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005525static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005526supercheck(PyTypeObject *type, PyObject *obj)
5527{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005528 /* Check that a super() call makes sense. Return a type object.
5529
5530 obj can be a new-style class, or an instance of one:
5531
5532 - If it is a class, it must be a subclass of 'type'. This case is
5533 used for class methods; the return value is obj.
5534
5535 - If it is an instance, it must be an instance of 'type'. This is
5536 the normal case; the return value is obj.__class__.
5537
5538 But... when obj is an instance, we want to allow for the case where
5539 obj->ob_type is not a subclass of type, but obj.__class__ is!
5540 This will allow using super() with a proxy for obj.
5541 */
5542
Guido van Rossum8e80a722003-02-18 19:22:22 +00005543 /* Check for first bullet above (special case) */
5544 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5545 Py_INCREF(obj);
5546 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005547 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005548
5549 /* Normal case */
5550 if (PyType_IsSubtype(obj->ob_type, type)) {
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005551 Py_INCREF(obj->ob_type);
5552 return obj->ob_type;
5553 }
5554 else {
5555 /* Try the slow way */
5556 static PyObject *class_str = NULL;
5557 PyObject *class_attr;
5558
5559 if (class_str == NULL) {
5560 class_str = PyString_FromString("__class__");
5561 if (class_str == NULL)
5562 return NULL;
5563 }
5564
5565 class_attr = PyObject_GetAttr(obj, class_str);
5566
5567 if (class_attr != NULL &&
5568 PyType_Check(class_attr) &&
5569 (PyTypeObject *)class_attr != obj->ob_type)
5570 {
5571 int ok = PyType_IsSubtype(
5572 (PyTypeObject *)class_attr, type);
5573 if (ok)
5574 return (PyTypeObject *)class_attr;
5575 }
5576
5577 if (class_attr == NULL)
5578 PyErr_Clear();
5579 else
5580 Py_DECREF(class_attr);
5581 }
5582
Tim Peters97e5ff52003-02-18 19:32:50 +00005583 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005584 "super(type, obj): "
5585 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005586 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005587}
5588
Guido van Rossum705f0f52001-08-24 16:47:00 +00005589static PyObject *
5590super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5591{
5592 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005593 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005594
5595 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5596 /* Not binding to an object, or already bound */
5597 Py_INCREF(self);
5598 return self;
5599 }
Guido van Rossum5b443c62001-12-03 15:38:28 +00005600 if (su->ob_type != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005601 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005602 call its type */
Thomas Wouters477c8d52006-05-27 19:21:47 +00005603 return PyObject_CallFunctionObjArgs((PyObject *)su->ob_type,
5604 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005605 else {
5606 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005607 PyTypeObject *obj_type = supercheck(su->type, obj);
5608 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005609 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005610 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005611 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005612 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005613 return NULL;
5614 Py_INCREF(su->type);
5615 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005616 newobj->type = su->type;
5617 newobj->obj = obj;
5618 newobj->obj_type = obj_type;
5619 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005620 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005621}
5622
5623static int
5624super_init(PyObject *self, PyObject *args, PyObject *kwds)
5625{
5626 superobject *su = (superobject *)self;
Guido van Rossume705ef12001-08-29 15:47:06 +00005627 PyTypeObject *type;
5628 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005629 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005630
Thomas Wouters89f507f2006-12-13 04:49:30 +00005631 if (!_PyArg_NoKeywords("super", kwds))
5632 return -1;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005633 if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5634 return -1;
5635 if (obj == Py_None)
5636 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005637 if (obj != NULL) {
5638 obj_type = supercheck(type, obj);
5639 if (obj_type == NULL)
5640 return -1;
5641 Py_INCREF(obj);
5642 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005643 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005644 su->type = type;
5645 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005646 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005647 return 0;
5648}
5649
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005650PyDoc_STRVAR(super_doc,
Guido van Rossum705f0f52001-08-24 16:47:00 +00005651"super(type) -> unbound super object\n"
5652"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005653"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005654"Typical use to call a cooperative superclass method:\n"
5655"class C(B):\n"
5656" def meth(self, arg):\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005657" super(C, self).meth(arg)");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005658
Guido van Rossum048eb752001-10-02 21:24:57 +00005659static int
5660super_traverse(PyObject *self, visitproc visit, void *arg)
5661{
5662 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005663
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005664 Py_VISIT(su->obj);
5665 Py_VISIT(su->type);
5666 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005667
5668 return 0;
5669}
5670
Guido van Rossum705f0f52001-08-24 16:47:00 +00005671PyTypeObject PySuper_Type = {
5672 PyObject_HEAD_INIT(&PyType_Type)
5673 0, /* ob_size */
5674 "super", /* tp_name */
5675 sizeof(superobject), /* tp_basicsize */
5676 0, /* tp_itemsize */
5677 /* methods */
5678 super_dealloc, /* tp_dealloc */
5679 0, /* tp_print */
5680 0, /* tp_getattr */
5681 0, /* tp_setattr */
5682 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005683 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005684 0, /* tp_as_number */
5685 0, /* tp_as_sequence */
5686 0, /* tp_as_mapping */
5687 0, /* tp_hash */
5688 0, /* tp_call */
5689 0, /* tp_str */
5690 super_getattro, /* tp_getattro */
5691 0, /* tp_setattro */
5692 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005693 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5694 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005695 super_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00005696 super_traverse, /* tp_traverse */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005697 0, /* tp_clear */
5698 0, /* tp_richcompare */
5699 0, /* tp_weaklistoffset */
5700 0, /* tp_iter */
5701 0, /* tp_iternext */
5702 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005703 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005704 0, /* tp_getset */
5705 0, /* tp_base */
5706 0, /* tp_dict */
5707 super_descr_get, /* tp_descr_get */
5708 0, /* tp_descr_set */
5709 0, /* tp_dictoffset */
5710 super_init, /* tp_init */
5711 PyType_GenericAlloc, /* tp_alloc */
5712 PyType_GenericNew, /* tp_new */
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00005713 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005714};