blob: 3ad5efcfc1403cf923ed9cf23ca5bfd510091145 [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"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00004#include "frameobject.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00005#include "structmember.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Guido van Rossum9923ffe2002-06-04 19:52:53 +00007#include <ctype.h>
8
Guido van Rossum6f799372001-09-20 20:46:19 +00009static PyMemberDef type_members[] = {
Tim Peters6d6c1a32001-08-02 04:15:00 +000010 {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
11 {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
12 {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
Guido van Rossum9676b222001-08-17 20:32:36 +000013 {"__weakrefoffset__", T_LONG,
Tim Peters6d6c1a32001-08-02 04:15:00 +000014 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
15 {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
16 {"__dictoffset__", T_LONG,
17 offsetof(PyTypeObject, tp_dictoffset), READONLY},
Tim Peters6d6c1a32001-08-02 04:15:00 +000018 {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
19 {0}
20};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossumc0b618a1997-05-02 03:12:38 +000022static PyObject *
Guido van Rossumc3542212001-08-16 09:18:56 +000023type_name(PyTypeObject *type, void *context)
24{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +000025 const char *s;
Guido van Rossumc3542212001-08-16 09:18:56 +000026
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000027 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
Guido van Rossume5c691a2003-03-07 15:13:17 +000028 PyHeapTypeObject* et = (PyHeapTypeObject*)type;
Tim Petersea7f75d2002-12-07 21:39:16 +000029
Georg Brandlc255c7b2006-02-20 22:27:28 +000030 Py_INCREF(et->ht_name);
31 return et->ht_name;
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000032 }
33 else {
34 s = strrchr(type->tp_name, '.');
35 if (s == NULL)
36 s = type->tp_name;
37 else
38 s++;
Martin v. Löwis5b222132007-06-10 09:51:05 +000039 return PyUnicode_FromString(s);
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000040 }
Guido van Rossumc3542212001-08-16 09:18:56 +000041}
42
Michael W. Hudson98bbc492002-11-26 14:47:27 +000043static int
44type_set_name(PyTypeObject *type, PyObject *value, void *context)
45{
Guido van Rossume5c691a2003-03-07 15:13:17 +000046 PyHeapTypeObject* et;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000047
48 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
49 PyErr_Format(PyExc_TypeError,
50 "can't set %s.__name__", type->tp_name);
51 return -1;
52 }
53 if (!value) {
54 PyErr_Format(PyExc_TypeError,
55 "can't delete %s.__name__", type->tp_name);
56 return -1;
57 }
Thomas Hellerace8ba82007-07-11 20:01:43 +000058 if (PyUnicode_Check(value)) {
59 value = _PyUnicode_AsDefaultEncodedString(value, NULL);
Guido van Rossum55b4a7b2007-07-11 09:28:11 +000060 if (value == NULL)
61 return -1;
62 }
Thomas Hellerace8ba82007-07-11 20:01:43 +000063 if (!PyString_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +000064 PyErr_Format(PyExc_TypeError,
65 "can only assign string to %s.__name__, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000066 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000067 return -1;
68 }
Thomas Hellerace8ba82007-07-11 20:01:43 +000069 if (strlen(PyString_AS_STRING(value))
70 != (size_t)PyString_GET_SIZE(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +000071 PyErr_Format(PyExc_ValueError,
72 "__name__ must not contain null bytes");
73 return -1;
74 }
75
Guido van Rossume5c691a2003-03-07 15:13:17 +000076 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000077
78 Py_INCREF(value);
79
Georg Brandlc255c7b2006-02-20 22:27:28 +000080 Py_DECREF(et->ht_name);
81 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000082
Thomas Hellerace8ba82007-07-11 20:01:43 +000083 type->tp_name = PyString_AS_STRING(value);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000084
85 return 0;
86}
87
Guido van Rossumc3542212001-08-16 09:18:56 +000088static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000089type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000090{
Guido van Rossumc3542212001-08-16 09:18:56 +000091 PyObject *mod;
92 char *s;
93
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000094 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
95 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000096 if (!mod) {
97 PyErr_Format(PyExc_AttributeError, "__module__");
98 return 0;
99 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000100 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +0000101 return mod;
102 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000103 else {
104 s = strrchr(type->tp_name, '.');
105 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000106 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000107 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Martin v. Löwis5b222132007-06-10 09:51:05 +0000108 return PyUnicode_FromString("__builtin__");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000109 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110}
111
Guido van Rossum3926a632001-09-25 16:25:58 +0000112static int
113type_set_module(PyTypeObject *type, PyObject *value, void *context)
114{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000115 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000116 PyErr_Format(PyExc_TypeError,
117 "can't set %s.__module__", type->tp_name);
118 return -1;
119 }
120 if (!value) {
121 PyErr_Format(PyExc_TypeError,
122 "can't delete %s.__module__", type->tp_name);
123 return -1;
124 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000125
Guido van Rossum3926a632001-09-25 16:25:58 +0000126 return PyDict_SetItemString(type->tp_dict, "__module__", value);
127}
128
Tim Peters6d6c1a32001-08-02 04:15:00 +0000129static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000130type_get_bases(PyTypeObject *type, void *context)
131{
132 Py_INCREF(type->tp_bases);
133 return type->tp_bases;
134}
135
136static PyTypeObject *best_base(PyObject *);
137static int mro_internal(PyTypeObject *);
138static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
139static int add_subclass(PyTypeObject*, PyTypeObject*);
140static void remove_subclass(PyTypeObject *, PyTypeObject *);
141static void update_all_slots(PyTypeObject *);
142
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000143typedef int (*update_callback)(PyTypeObject *, void *);
144static int update_subclasses(PyTypeObject *type, PyObject *name,
145 update_callback callback, void *data);
146static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
147 update_callback callback, void *data);
148
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000150mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000151{
152 PyTypeObject *subclass;
153 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000154 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000155
156 subclasses = type->tp_subclasses;
157 if (subclasses == NULL)
158 return 0;
159 assert(PyList_Check(subclasses));
160 n = PyList_GET_SIZE(subclasses);
161 for (i = 0; i < n; i++) {
162 ref = PyList_GET_ITEM(subclasses, i);
163 assert(PyWeakref_CheckRef(ref));
164 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
165 assert(subclass != NULL);
166 if ((PyObject *)subclass == Py_None)
167 continue;
168 assert(PyType_Check(subclass));
169 old_mro = subclass->tp_mro;
170 if (mro_internal(subclass) < 0) {
171 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000172 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000173 }
174 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000175 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000176 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000177 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000178 if (!tuple)
179 return -1;
180 if (PyList_Append(temp, tuple) < 0)
181 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000182 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000183 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000184 if (mro_subclasses(subclass, temp) < 0)
185 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000186 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000187 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000188}
189
190static int
191type_set_bases(PyTypeObject *type, PyObject *value, void *context)
192{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000193 Py_ssize_t i;
194 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000195 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000196 PyTypeObject *new_base, *old_base;
197 PyObject *old_bases, *old_mro;
198
199 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
200 PyErr_Format(PyExc_TypeError,
201 "can't set %s.__bases__", type->tp_name);
202 return -1;
203 }
204 if (!value) {
205 PyErr_Format(PyExc_TypeError,
206 "can't delete %s.__bases__", type->tp_name);
207 return -1;
208 }
209 if (!PyTuple_Check(value)) {
210 PyErr_Format(PyExc_TypeError,
211 "can only assign tuple to %s.__bases__, not %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000212 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000213 return -1;
214 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000215 if (PyTuple_GET_SIZE(value) == 0) {
216 PyErr_Format(PyExc_TypeError,
217 "can only assign non-empty tuple to %s.__bases__, not ()",
218 type->tp_name);
219 return -1;
220 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000221 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
222 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000223 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000224 PyErr_Format(
225 PyExc_TypeError,
226 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000227 type->tp_name, Py_Type(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000228 return -1;
229 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000230 if (PyType_Check(ob)) {
231 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
232 PyErr_SetString(PyExc_TypeError,
233 "a __bases__ item causes an inheritance cycle");
234 return -1;
235 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000236 }
237 }
238
239 new_base = best_base(value);
240
241 if (!new_base) {
242 return -1;
243 }
244
245 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
246 return -1;
247
248 Py_INCREF(new_base);
249 Py_INCREF(value);
250
251 old_bases = type->tp_bases;
252 old_base = type->tp_base;
253 old_mro = type->tp_mro;
254
255 type->tp_bases = value;
256 type->tp_base = new_base;
257
258 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000259 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000260 }
261
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000262 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000263 if (!temp)
264 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000265
266 r = mro_subclasses(type, temp);
267
268 if (r < 0) {
269 for (i = 0; i < PyList_Size(temp); i++) {
270 PyTypeObject* cls;
271 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000272 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
273 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000274 Py_INCREF(mro);
275 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000276 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000278 }
279 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000280 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000281 }
282
283 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000284
285 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000286 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000287 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000288 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000289
290 /* for now, sod that: just remove from all old_bases,
291 add to all new_bases */
292
293 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
294 ob = PyTuple_GET_ITEM(old_bases, i);
295 if (PyType_Check(ob)) {
296 remove_subclass(
297 (PyTypeObject*)ob, type);
298 }
299 }
300
301 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
302 ob = PyTuple_GET_ITEM(value, i);
303 if (PyType_Check(ob)) {
304 if (add_subclass((PyTypeObject*)ob, type) < 0)
305 r = -1;
306 }
307 }
308
309 update_all_slots(type);
310
311 Py_DECREF(old_bases);
312 Py_DECREF(old_base);
313 Py_DECREF(old_mro);
314
315 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000316
317 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000318 Py_DECREF(type->tp_bases);
319 Py_DECREF(type->tp_base);
320 if (type->tp_mro != old_mro) {
321 Py_DECREF(type->tp_mro);
322 }
323
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000324 type->tp_bases = old_bases;
325 type->tp_base = old_base;
326 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000327
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000328 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000329}
330
331static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000332type_dict(PyTypeObject *type, void *context)
333{
334 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 Py_INCREF(Py_None);
336 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000337 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000338 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000339}
340
Tim Peters24008312002-03-17 18:56:20 +0000341static PyObject *
342type_get_doc(PyTypeObject *type, void *context)
343{
344 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000345 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Tim Peters24008312002-03-17 18:56:20 +0000346 return PyString_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000347 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000348 if (result == NULL) {
349 result = Py_None;
350 Py_INCREF(result);
351 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000352 else if (Py_Type(result)->tp_descr_get) {
353 result = Py_Type(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000354 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000355 }
356 else {
357 Py_INCREF(result);
358 }
Tim Peters24008312002-03-17 18:56:20 +0000359 return result;
360}
361
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000362static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000363 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
364 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000365 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000366 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000367 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000368 {0}
369};
370
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000372type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000374 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000375 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000376
377 mod = type_module(type, NULL);
378 if (mod == NULL)
379 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000380 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000381 Py_DECREF(mod);
382 mod = NULL;
383 }
384 name = type_name(type, NULL);
385 if (name == NULL)
386 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000387
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000388 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
389 kind = "class";
390 else
391 kind = "type";
392
Walter Dörwald75163602007-06-11 15:47:13 +0000393 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "__builtin__"))
394 rtn = PyUnicode_FromFormat("<%s '%U.%U'>", kind, mod, name);
Guido van Rossumc3542212001-08-16 09:18:56 +0000395 else
Walter Dörwald1ab83302007-05-18 17:15:44 +0000396 rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000397
Guido van Rossumc3542212001-08-16 09:18:56 +0000398 Py_XDECREF(mod);
399 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000400 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401}
402
Tim Peters6d6c1a32001-08-02 04:15:00 +0000403static PyObject *
404type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
405{
406 PyObject *obj;
407
408 if (type->tp_new == NULL) {
409 PyErr_Format(PyExc_TypeError,
410 "cannot create '%.100s' instances",
411 type->tp_name);
412 return NULL;
413 }
414
Tim Peters3f996e72001-09-13 19:18:27 +0000415 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000416 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000417 /* Ugly exception: when the call was type(something),
418 don't call tp_init on the result. */
419 if (type == &PyType_Type &&
420 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
421 (kwds == NULL ||
422 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
423 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000424 /* If the returned object is not an instance of type,
425 it won't be initialized. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000426 if (!PyType_IsSubtype(Py_Type(obj), type))
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000427 return obj;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000428 type = Py_Type(obj);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000429 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000430 type->tp_init(obj, args, kwds) < 0) {
431 Py_DECREF(obj);
432 obj = NULL;
433 }
434 }
435 return obj;
436}
437
438PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000440{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000441 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000442 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
443 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000444
445 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000446 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000448 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000449
Neil Schemenauerc806c882001-08-29 23:54:54 +0000450 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000451 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Neil Schemenauerc806c882001-08-29 23:54:54 +0000453 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000454
Tim Peters6d6c1a32001-08-02 04:15:00 +0000455 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
456 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000457
Tim Peters6d6c1a32001-08-02 04:15:00 +0000458 if (type->tp_itemsize == 0)
459 PyObject_INIT(obj, type);
460 else
461 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000462
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000464 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000465 return obj;
466}
467
468PyObject *
469PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
470{
471 return type->tp_alloc(type, 0);
472}
473
Guido van Rossum9475a232001-10-05 20:51:39 +0000474/* Helpers for subtyping */
475
476static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000477traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
478{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000479 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000480 PyMemberDef *mp;
481
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000482 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000483 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000484 for (i = 0; i < n; i++, mp++) {
485 if (mp->type == T_OBJECT_EX) {
486 char *addr = (char *)self + mp->offset;
487 PyObject *obj = *(PyObject **)addr;
488 if (obj != NULL) {
489 int err = visit(obj, arg);
490 if (err)
491 return err;
492 }
493 }
494 }
495 return 0;
496}
497
498static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000499subtype_traverse(PyObject *self, visitproc visit, void *arg)
500{
501 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000503
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000504 /* Find the nearest base with a different tp_traverse,
505 and traverse slots while we're at it */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000506 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000507 base = type;
508 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000509 if (Py_Size(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000510 int err = traverse_slots(base, self, visit, arg);
511 if (err)
512 return err;
513 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000514 base = base->tp_base;
515 assert(base);
516 }
517
518 if (type->tp_dictoffset != base->tp_dictoffset) {
519 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000520 if (dictptr && *dictptr)
521 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000522 }
523
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000524 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000525 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000527 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000529
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000530 if (basetraverse)
531 return basetraverse(self, visit, arg);
532 return 0;
533}
534
535static void
536clear_slots(PyTypeObject *type, PyObject *self)
537{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000538 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000539 PyMemberDef *mp;
540
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000541 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000542 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000543 for (i = 0; i < n; i++, mp++) {
544 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
545 char *addr = (char *)self + mp->offset;
546 PyObject *obj = *(PyObject **)addr;
547 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000548 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000549 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000550 }
551 }
552 }
553}
554
555static int
556subtype_clear(PyObject *self)
557{
558 PyTypeObject *type, *base;
559 inquiry baseclear;
560
561 /* Find the nearest base with a different tp_clear
562 and clear slots while we're at it */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000563 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000564 base = type;
565 while ((baseclear = base->tp_clear) == subtype_clear) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000566 if (Py_Size(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000567 clear_slots(base, self);
568 base = base->tp_base;
569 assert(base);
570 }
571
Guido van Rossuma3862092002-06-10 15:24:42 +0000572 /* There's no need to clear the instance dict (if any);
573 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000574
575 if (baseclear)
576 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000577 return 0;
578}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000579
580static void
581subtype_dealloc(PyObject *self)
582{
Guido van Rossum14227b42001-12-06 02:35:58 +0000583 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000584 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000585
Guido van Rossum22b13872002-08-06 21:41:44 +0000586 /* Extract the type; we expect it to be a heap type */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000587 type = Py_Type(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000589
Guido van Rossum22b13872002-08-06 21:41:44 +0000590 /* Test whether the type has GC exactly once */
591
592 if (!PyType_IS_GC(type)) {
593 /* It's really rare to find a dynamic type that doesn't have
594 GC; it can only happen when deriving from 'object' and not
595 adding any slots or instance variables. This allows
596 certain simplifications: there's no need to call
597 clear_slots(), or DECREF the dict, or clear weakrefs. */
598
599 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000600 if (type->tp_del) {
601 type->tp_del(self);
602 if (self->ob_refcnt > 0)
603 return;
604 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000605
606 /* Find the nearest base with a different tp_dealloc */
607 base = type;
608 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000609 assert(Py_Size(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000610 base = base->tp_base;
611 assert(base);
612 }
613
614 /* Call the base tp_dealloc() */
615 assert(basedealloc);
616 basedealloc(self);
617
618 /* Can't reference self beyond this point */
619 Py_DECREF(type);
620
621 /* Done */
622 return;
623 }
624
625 /* We get here only if the type has GC */
626
627 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000628 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000629 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000630 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000631 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000632 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000633 /* DO NOT restore GC tracking at this point. weakref callbacks
634 * (if any, and whether directly here or indirectly in something we
635 * call) may trigger GC, and if self is tracked at that point, it
636 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000637 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000638
Guido van Rossum59195fd2003-06-13 20:54:40 +0000639 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000640 base = type;
641 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000642 base = base->tp_base;
643 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000644 }
645
Guido van Rossumd8faa362007-04-27 19:54:29 +0000646 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000647 the finalizer (__del__), clearing slots, or clearing the instance
648 dict. */
649
Guido van Rossum1987c662003-05-29 14:29:23 +0000650 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
651 PyObject_ClearWeakRefs(self);
652
653 /* Maybe call finalizer; exit early if resurrected */
654 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000655 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000656 type->tp_del(self);
657 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000658 goto endlabel; /* resurrected */
659 else
660 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000661 /* New weakrefs could be created during the finalizer call.
662 If this occurs, clear them out without calling their
663 finalizers since they might rely on part of the object
664 being finalized that has already been destroyed. */
665 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
666 /* Modeled after GET_WEAKREFS_LISTPTR() */
667 PyWeakReference **list = (PyWeakReference **) \
668 PyObject_GET_WEAKREFS_LISTPTR(self);
669 while (*list)
670 _PyWeakref_ClearRef(*list);
671 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000672 }
673
Guido van Rossum59195fd2003-06-13 20:54:40 +0000674 /* Clear slots up to the nearest base with a different tp_dealloc */
675 base = type;
676 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000677 if (Py_Size(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000678 clear_slots(base, self);
679 base = base->tp_base;
680 assert(base);
681 }
682
Tim Peters6d6c1a32001-08-02 04:15:00 +0000683 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000684 if (type->tp_dictoffset && !base->tp_dictoffset) {
685 PyObject **dictptr = _PyObject_GetDictPtr(self);
686 if (dictptr != NULL) {
687 PyObject *dict = *dictptr;
688 if (dict != NULL) {
689 Py_DECREF(dict);
690 *dictptr = NULL;
691 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000692 }
693 }
694
Tim Peters0bd743c2003-11-13 22:50:00 +0000695 /* Call the base tp_dealloc(); first retrack self if
696 * basedealloc knows about gc.
697 */
698 if (PyType_IS_GC(base))
699 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000700 assert(basedealloc);
701 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000702
703 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000704 Py_DECREF(type);
705
Guido van Rossum0906e072002-08-07 20:42:09 +0000706 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000707 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000708 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000709 --_PyTrash_delete_nesting;
710
711 /* Explanation of the weirdness around the trashcan macros:
712
713 Q. What do the trashcan macros do?
714
715 A. Read the comment titled "Trashcan mechanism" in object.h.
716 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000718 trashcan code, the answers to the following questions don't make
719 sense.
720
721 Q. Why do we GC-untrack before the trashcan and then immediately
722 GC-track again afterward?
723
724 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000725 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000726 UNTRACK macro, this will crash when the object is already
727 untracked. Because we don't know what the base class does, the
728 only safe thing is to make sure the object is tracked when we
729 call the base class dealloc. But... The trashcan begin macro
730 requires that the object is *untracked* before it is called. So
731 the dance becomes:
732
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000734 trashcan begin
735 GC track
736
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737 Q. Why did the last question say "immediately GC-track again"?
738 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000739
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 A. Because the code *used* to re-track immediately. Bad Idea.
741 self has a refcount of 0, and if gc ever gets its hands on it
742 (which can happen if any weakref callback gets invoked), it
743 looks like trash to gc too, and gc also tries to delete self
744 then. But we're already deleting self. Double dealloction is
745 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000746
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000747 Q. Why the bizarre (net-zero) manipulation of
748 _PyTrash_delete_nesting around the trashcan macros?
749
750 A. Some base classes (e.g. list) also use the trashcan mechanism.
751 The following scenario used to be possible:
752
753 - suppose the trashcan level is one below the trashcan limit
754
755 - subtype_dealloc() is called
756
757 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 is incremented and the code between trashcan begin and end is
759 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000760
761 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000762 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000763
764 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000766
767 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000768 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000769
770 - basedealloc() returns
771
772 - subtype_dealloc() decrefs the object's type
773
774 - subtype_dealloc() returns
775
776 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000778
779 - subtype_dealloc() is called *AGAIN* for the same object
780
781 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +0000782 cause problems) the object's type gets decref'ed a second
783 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000784
785 The remedy is to make sure that if the code between trashcan
786 begin and end in subtype_dealloc() is called, the code between
787 trashcan begin and end in basedealloc() will also be called.
788 This is done by decrementing the level after passing into the
789 trashcan block, and incrementing it just before leaving the
790 block.
791
792 But now it's possible that a chain of objects consisting solely
793 of objects whose deallocator is subtype_dealloc() will defeat
794 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000796 *increment* the level *before* entering the trashcan block, and
797 matchingly decrement it after leaving. This means the trashcan
798 code will trigger a little early, but that's no big deal.
799
800 Q. Are there any live examples of code in need of all this
801 complexity?
802
803 A. Yes. See SF bug 668433 for code that crashed (when Python was
804 compiled in debug mode) before the trashcan level manipulations
805 were added. For more discussion, see SF patches 581742, 575073
806 and bug 574207.
807 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000808}
809
Jeremy Hylton938ace62002-07-17 16:30:39 +0000810static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000811
Tim Peters6d6c1a32001-08-02 04:15:00 +0000812/* type test with subclassing support */
813
814int
815PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
816{
817 PyObject *mro;
818
819 mro = a->tp_mro;
820 if (mro != NULL) {
821 /* Deal with multiple inheritance without recursion
822 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000823 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 assert(PyTuple_Check(mro));
825 n = PyTuple_GET_SIZE(mro);
826 for (i = 0; i < n; i++) {
827 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
828 return 1;
829 }
830 return 0;
831 }
832 else {
833 /* a is not completely initilized yet; follow tp_base */
834 do {
835 if (a == b)
836 return 1;
837 a = a->tp_base;
838 } while (a != NULL);
839 return b == &PyBaseObject_Type;
840 }
841}
842
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000843/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000844 without looking in the instance dictionary
845 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000847 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000848 static variable used to cache the interned Python string.
849
850 Two variants:
851
852 - lookup_maybe() returns NULL without raising an exception
853 when the _PyType_Lookup() call fails;
854
855 - lookup_method() always raises an exception upon errors.
856*/
Guido van Rossum60718732001-08-28 17:47:51 +0000857
858static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000859lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000860{
861 PyObject *res;
862
863 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000864 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +0000865 if (*attrobj == NULL)
866 return NULL;
867 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000868 res = _PyType_Lookup(Py_Type(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000869 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000870 descrgetfunc f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000871 if ((f = Py_Type(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +0000872 Py_INCREF(res);
873 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000874 res = f(res, self, (PyObject *)(Py_Type(self)));
Guido van Rossum60718732001-08-28 17:47:51 +0000875 }
876 return res;
877}
878
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000879static PyObject *
880lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
881{
882 PyObject *res = lookup_maybe(self, attrstr, attrobj);
883 if (res == NULL && !PyErr_Occurred())
884 PyErr_SetObject(PyExc_AttributeError, *attrobj);
885 return res;
886}
887
Guido van Rossum2730b132001-08-28 18:22:14 +0000888/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000890 as lookup_method to cache the interned name string object. */
891
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000892static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000893call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
894{
895 va_list va;
896 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000897 va_start(va, format);
898
Guido van Rossumda21c012001-10-03 00:50:18 +0000899 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000900 if (func == NULL) {
901 va_end(va);
902 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000903 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000904 return NULL;
905 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000906
907 if (format && *format)
908 args = Py_VaBuildValue(format, va);
909 else
910 args = PyTuple_New(0);
911
912 va_end(va);
913
914 if (args == NULL)
915 return NULL;
916
917 assert(PyTuple_Check(args));
918 retval = PyObject_Call(func, args, NULL);
919
920 Py_DECREF(args);
921 Py_DECREF(func);
922
923 return retval;
924}
925
926/* Clone of call_method() that returns NotImplemented when the lookup fails. */
927
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000928static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000929call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
930{
931 va_list va;
932 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000933 va_start(va, format);
934
Guido van Rossumda21c012001-10-03 00:50:18 +0000935 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000936 if (func == NULL) {
937 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000938 if (!PyErr_Occurred()) {
939 Py_INCREF(Py_NotImplemented);
940 return Py_NotImplemented;
941 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000942 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000943 }
944
945 if (format && *format)
946 args = Py_VaBuildValue(format, va);
947 else
948 args = PyTuple_New(0);
949
950 va_end(va);
951
Guido van Rossum717ce002001-09-14 16:58:08 +0000952 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000953 return NULL;
954
Guido van Rossum717ce002001-09-14 16:58:08 +0000955 assert(PyTuple_Check(args));
956 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000957
958 Py_DECREF(args);
959 Py_DECREF(func);
960
961 return retval;
962}
963
Tim Petersea7f75d2002-12-07 21:39:16 +0000964/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000965 Method resolution order algorithm C3 described in
966 "A Monotonic Superclass Linearization for Dylan",
967 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000968 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000969 (OOPSLA 1996)
970
Guido van Rossum98f33732002-11-25 21:36:54 +0000971 Some notes about the rules implied by C3:
972
Tim Petersea7f75d2002-12-07 21:39:16 +0000973 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000974 It isn't legal to repeat a class in a list of base classes.
975
976 The next three properties are the 3 constraints in "C3".
977
Tim Petersea7f75d2002-12-07 21:39:16 +0000978 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000979 If A precedes B in C's MRO, then A will precede B in the MRO of all
980 subclasses of C.
981
982 Monotonicity.
983 The MRO of a class must be an extension without reordering of the
984 MRO of each of its superclasses.
985
986 Extended Precedence Graph (EPG).
987 Linearization is consistent if there is a path in the EPG from
988 each class to all its successors in the linearization. See
989 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000990 */
991
Tim Petersea7f75d2002-12-07 21:39:16 +0000992static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000993tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000994 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +0000995 size = PyList_GET_SIZE(list);
996
997 for (j = whence+1; j < size; j++) {
998 if (PyList_GET_ITEM(list, j) == o)
999 return 1;
1000 }
1001 return 0;
1002}
1003
Guido van Rossum98f33732002-11-25 21:36:54 +00001004static PyObject *
1005class_name(PyObject *cls)
1006{
1007 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1008 if (name == NULL) {
1009 PyErr_Clear();
1010 Py_XDECREF(name);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001011 name = PyObject_ReprStr8(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001012 }
1013 if (name == NULL)
1014 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001015 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001016 Py_DECREF(name);
1017 return NULL;
1018 }
1019 return name;
1020}
1021
1022static int
1023check_duplicates(PyObject *list)
1024{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001025 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001026 /* Let's use a quadratic time algorithm,
1027 assuming that the bases lists is short.
1028 */
1029 n = PyList_GET_SIZE(list);
1030 for (i = 0; i < n; i++) {
1031 PyObject *o = PyList_GET_ITEM(list, i);
1032 for (j = i + 1; j < n; j++) {
1033 if (PyList_GET_ITEM(list, j) == o) {
1034 o = class_name(o);
1035 PyErr_Format(PyExc_TypeError,
1036 "duplicate base class %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001037 o ? PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001038 Py_XDECREF(o);
1039 return -1;
1040 }
1041 }
1042 }
1043 return 0;
1044}
1045
1046/* Raise a TypeError for an MRO order disagreement.
1047
1048 It's hard to produce a good error message. In the absence of better
1049 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001050 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001051 order in which they should be put in the MRO, but it's hard to
1052 diagnose what constraint can't be satisfied.
1053*/
1054
1055static void
1056set_mro_error(PyObject *to_merge, int *remain)
1057{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001058 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001059 char buf[1000];
1060 PyObject *k, *v;
1061 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001062 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001063
1064 to_merge_size = PyList_GET_SIZE(to_merge);
1065 for (i = 0; i < to_merge_size; i++) {
1066 PyObject *L = PyList_GET_ITEM(to_merge, i);
1067 if (remain[i] < PyList_GET_SIZE(L)) {
1068 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069 if (PyDict_SetItem(set, c, Py_None) < 0) {
1070 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001071 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001072 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001073 }
1074 }
1075 n = PyDict_Size(set);
1076
Raymond Hettingerf394df42003-04-06 19:13:41 +00001077 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1078consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001080 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001081 PyObject *name = class_name(k);
1082 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001083 name ? PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001084 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001085 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001086 buf[off++] = ',';
1087 buf[off] = '\0';
1088 }
1089 }
1090 PyErr_SetString(PyExc_TypeError, buf);
1091 Py_DECREF(set);
1092}
1093
Tim Petersea7f75d2002-12-07 21:39:16 +00001094static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001095pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001097 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001098 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001099
Guido van Rossum1f121312002-11-14 19:49:16 +00001100 to_merge_size = PyList_GET_SIZE(to_merge);
1101
Guido van Rossum98f33732002-11-25 21:36:54 +00001102 /* remain stores an index into each sublist of to_merge.
1103 remain[i] is the index of the next base in to_merge[i]
1104 that is not included in acc.
1105 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001106 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001107 if (remain == NULL)
1108 return -1;
1109 for (i = 0; i < to_merge_size; i++)
1110 remain[i] = 0;
1111
1112 again:
1113 empty_cnt = 0;
1114 for (i = 0; i < to_merge_size; i++) {
1115 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001116
Guido van Rossum1f121312002-11-14 19:49:16 +00001117 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1118
1119 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1120 empty_cnt++;
1121 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001123
Guido van Rossum98f33732002-11-25 21:36:54 +00001124 /* Choose next candidate for MRO.
1125
1126 The input sequences alone can determine the choice.
1127 If not, choose the class which appears in the MRO
1128 of the earliest direct superclass of the new class.
1129 */
1130
Guido van Rossum1f121312002-11-14 19:49:16 +00001131 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1132 for (j = 0; j < to_merge_size; j++) {
1133 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001136 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001137 }
1138 ok = PyList_Append(acc, candidate);
1139 if (ok < 0) {
1140 PyMem_Free(remain);
1141 return -1;
1142 }
1143 for (j = 0; j < to_merge_size; j++) {
1144 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001145 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1146 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001147 remain[j]++;
1148 }
1149 }
1150 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001151 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001152 }
1153
Guido van Rossum98f33732002-11-25 21:36:54 +00001154 if (empty_cnt == to_merge_size) {
1155 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001156 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001157 }
1158 set_mro_error(to_merge, remain);
1159 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001160 return -1;
1161}
1162
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163static PyObject *
1164mro_implementation(PyTypeObject *type)
1165{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166 Py_ssize_t i, n;
1167 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001169 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170
Guido van Rossum63517572002-06-18 16:44:57 +00001171 if(type->tp_dict == NULL) {
1172 if(PyType_Ready(type) < 0)
1173 return NULL;
1174 }
1175
Guido van Rossum98f33732002-11-25 21:36:54 +00001176 /* Find a superclass linearization that honors the constraints
1177 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001178 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001179
1180 to_merge is a list of lists, where each list is a superclass
1181 linearization implied by a base class. The last element of
1182 to_merge is the declared list of bases.
1183 */
1184
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185 bases = type->tp_bases;
1186 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001187
1188 to_merge = PyList_New(n+1);
1189 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001191
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001193 PyObject *base = PyTuple_GET_ITEM(bases, i);
1194 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001195 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001197 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001198 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001200
1201 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001203
1204 bases_aslist = PySequence_List(bases);
1205 if (bases_aslist == NULL) {
1206 Py_DECREF(to_merge);
1207 return NULL;
1208 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001209 /* This is just a basic sanity check. */
1210 if (check_duplicates(bases_aslist) < 0) {
1211 Py_DECREF(to_merge);
1212 Py_DECREF(bases_aslist);
1213 return NULL;
1214 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001215 PyList_SET_ITEM(to_merge, n, bases_aslist);
1216
1217 result = Py_BuildValue("[O]", (PyObject *)type);
1218 if (result == NULL) {
1219 Py_DECREF(to_merge);
1220 return NULL;
1221 }
1222
1223 ok = pmerge(result, to_merge);
1224 Py_DECREF(to_merge);
1225 if (ok < 0) {
1226 Py_DECREF(result);
1227 return NULL;
1228 }
1229
Tim Peters6d6c1a32001-08-02 04:15:00 +00001230 return result;
1231}
1232
1233static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001234mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001235{
1236 PyTypeObject *type = (PyTypeObject *)self;
1237
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 return mro_implementation(type);
1239}
1240
1241static int
1242mro_internal(PyTypeObject *type)
1243{
1244 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001245 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001247 if (Py_Type(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248 result = mro_implementation(type);
1249 }
1250 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001251 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001252 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001253 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 if (mro == NULL)
1255 return -1;
1256 result = PyObject_CallObject(mro, NULL);
1257 Py_DECREF(mro);
1258 }
1259 if (result == NULL)
1260 return -1;
1261 tuple = PySequence_Tuple(result);
1262 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001263 if (tuple == NULL)
1264 return -1;
1265 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001266 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001267 PyObject *cls;
1268 PyTypeObject *solid;
1269
1270 solid = solid_base(type);
1271
1272 len = PyTuple_GET_SIZE(tuple);
1273
1274 for (i = 0; i < len; i++) {
1275 PyTypeObject *t;
1276 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001277 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001278 PyErr_Format(PyExc_TypeError,
1279 "mro() returned a non-class ('%.500s')",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001280 Py_Type(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001281 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001282 return -1;
1283 }
1284 t = (PyTypeObject*)cls;
1285 if (!PyType_IsSubtype(solid, solid_base(t))) {
1286 PyErr_Format(PyExc_TypeError,
1287 "mro() returned base with unsuitable layout ('%.500s')",
1288 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001289 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001290 return -1;
1291 }
1292 }
1293 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 type->tp_mro = tuple;
1295 return 0;
1296}
1297
1298
1299/* Calculate the best base amongst multiple base classes.
1300 This is the first one that's on the path to the "solid base". */
1301
1302static PyTypeObject *
1303best_base(PyObject *bases)
1304{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001305 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001307 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308
1309 assert(PyTuple_Check(bases));
1310 n = PyTuple_GET_SIZE(bases);
1311 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001312 base = NULL;
1313 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001315 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001316 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317 PyErr_SetString(
1318 PyExc_TypeError,
1319 "bases must be types");
1320 return NULL;
1321 }
Tim Petersa91e9642001-11-14 23:32:33 +00001322 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001324 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 return NULL;
1326 }
1327 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001328 if (winner == NULL) {
1329 winner = candidate;
1330 base = base_i;
1331 }
1332 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333 ;
1334 else if (PyType_IsSubtype(candidate, winner)) {
1335 winner = candidate;
1336 base = base_i;
1337 }
1338 else {
1339 PyErr_SetString(
1340 PyExc_TypeError,
1341 "multiple bases have "
1342 "instance lay-out conflict");
1343 return NULL;
1344 }
1345 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001346 if (base == NULL)
1347 PyErr_SetString(PyExc_TypeError,
1348 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 return base;
1350}
1351
1352static int
1353extra_ivars(PyTypeObject *type, PyTypeObject *base)
1354{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001355 size_t t_size = type->tp_basicsize;
1356 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357
Guido van Rossum9676b222001-08-17 20:32:36 +00001358 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 if (type->tp_itemsize || base->tp_itemsize) {
1360 /* If itemsize is involved, stricter rules */
1361 return t_size != b_size ||
1362 type->tp_itemsize != base->tp_itemsize;
1363 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001364 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001365 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1366 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001367 t_size -= sizeof(PyObject *);
1368 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001369 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1370 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001371 t_size -= sizeof(PyObject *);
1372
1373 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374}
1375
1376static PyTypeObject *
1377solid_base(PyTypeObject *type)
1378{
1379 PyTypeObject *base;
1380
1381 if (type->tp_base)
1382 base = solid_base(type->tp_base);
1383 else
1384 base = &PyBaseObject_Type;
1385 if (extra_ivars(type, base))
1386 return type;
1387 else
1388 return base;
1389}
1390
Jeremy Hylton938ace62002-07-17 16:30:39 +00001391static void object_dealloc(PyObject *);
1392static int object_init(PyObject *, PyObject *, PyObject *);
1393static int update_slot(PyTypeObject *, PyObject *);
1394static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395
Guido van Rossum360e4b82007-05-14 22:51:27 +00001396/*
1397 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1398 * inherited from various builtin types. The builtin base usually provides
1399 * its own __dict__ descriptor, so we use that when we can.
1400 */
1401static PyTypeObject *
1402get_builtin_base_with_dict(PyTypeObject *type)
1403{
1404 while (type->tp_base != NULL) {
1405 if (type->tp_dictoffset != 0 &&
1406 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1407 return type;
1408 type = type->tp_base;
1409 }
1410 return NULL;
1411}
1412
1413static PyObject *
1414get_dict_descriptor(PyTypeObject *type)
1415{
1416 static PyObject *dict_str;
1417 PyObject *descr;
1418
1419 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001420 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001421 if (dict_str == NULL)
1422 return NULL;
1423 }
1424 descr = _PyType_Lookup(type, dict_str);
1425 if (descr == NULL || !PyDescr_IsData(descr))
1426 return NULL;
1427
1428 return descr;
1429}
1430
1431static void
1432raise_dict_descr_error(PyObject *obj)
1433{
1434 PyErr_Format(PyExc_TypeError,
1435 "this __dict__ descriptor does not support "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001436 "'%.200s' objects", Py_Type(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001437}
1438
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001440subtype_dict(PyObject *obj, void *context)
1441{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001442 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001444 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001445
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001446 base = get_builtin_base_with_dict(Py_Type(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001447 if (base != NULL) {
1448 descrgetfunc func;
1449 PyObject *descr = get_dict_descriptor(base);
1450 if (descr == NULL) {
1451 raise_dict_descr_error(obj);
1452 return NULL;
1453 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001454 func = Py_Type(descr)->tp_descr_get;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001455 if (func == NULL) {
1456 raise_dict_descr_error(obj);
1457 return NULL;
1458 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001459 return func(descr, obj, (PyObject *)(Py_Type(obj)));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001460 }
1461
1462 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001463 if (dictptr == NULL) {
1464 PyErr_SetString(PyExc_AttributeError,
1465 "This object has no __dict__");
1466 return NULL;
1467 }
1468 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001469 if (dict == NULL)
1470 *dictptr = dict = PyDict_New();
1471 Py_XINCREF(dict);
1472 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001473}
1474
Guido van Rossum6661be32001-10-26 04:26:12 +00001475static int
1476subtype_setdict(PyObject *obj, PyObject *value, void *context)
1477{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001478 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001479 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001480 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001481
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001482 base = get_builtin_base_with_dict(Py_Type(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001483 if (base != NULL) {
1484 descrsetfunc func;
1485 PyObject *descr = get_dict_descriptor(base);
1486 if (descr == NULL) {
1487 raise_dict_descr_error(obj);
1488 return -1;
1489 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001490 func = Py_Type(descr)->tp_descr_set;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001491 if (func == NULL) {
1492 raise_dict_descr_error(obj);
1493 return -1;
1494 }
1495 return func(descr, obj, value);
1496 }
1497
1498 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001499 if (dictptr == NULL) {
1500 PyErr_SetString(PyExc_AttributeError,
1501 "This object has no __dict__");
1502 return -1;
1503 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001504 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001505 PyErr_Format(PyExc_TypeError,
1506 "__dict__ must be set to a dictionary, "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001507 "not a '%.200s'", Py_Type(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001508 return -1;
1509 }
1510 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001511 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001512 *dictptr = value;
1513 Py_XDECREF(dict);
1514 return 0;
1515}
1516
Guido van Rossumad47da02002-08-12 19:05:44 +00001517static PyObject *
1518subtype_getweakref(PyObject *obj, void *context)
1519{
1520 PyObject **weaklistptr;
1521 PyObject *result;
1522
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001523 if (Py_Type(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001525 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001526 return NULL;
1527 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001528 assert(Py_Type(obj)->tp_weaklistoffset > 0);
1529 assert(Py_Type(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1530 (size_t)(Py_Type(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 weaklistptr = (PyObject **)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001532 ((char *)obj + Py_Type(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001533 if (*weaklistptr == NULL)
1534 result = Py_None;
1535 else
1536 result = *weaklistptr;
1537 Py_INCREF(result);
1538 return result;
1539}
1540
Guido van Rossum373c7412003-01-07 13:41:37 +00001541/* Three variants on the subtype_getsets list. */
1542
1543static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001544 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001545 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001546 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001547 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001548 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001549};
1550
Guido van Rossum373c7412003-01-07 13:41:37 +00001551static PyGetSetDef subtype_getsets_dict_only[] = {
1552 {"__dict__", subtype_dict, subtype_setdict,
1553 PyDoc_STR("dictionary for instance variables (if defined)")},
1554 {0}
1555};
1556
1557static PyGetSetDef subtype_getsets_weakref_only[] = {
1558 {"__weakref__", subtype_getweakref, NULL,
1559 PyDoc_STR("list of weak references to the object (if defined)")},
1560 {0}
1561};
1562
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001563static int
1564valid_identifier(PyObject *s)
1565{
Walter Dörwald7815c5e2007-06-11 14:55:19 +00001566 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001567 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001568
Martin v. Löwis5b222132007-06-10 09:51:05 +00001569 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001570 PyErr_Format(PyExc_TypeError,
1571 "__slots__ items must be strings, not '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001572 Py_Type(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001573 return 0;
1574 }
Walter Dörwald7815c5e2007-06-11 14:55:19 +00001575 p = PyUnicode_AS_UNICODE(s);
1576 n = PyUnicode_GET_SIZE(s);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001577 /* We must reject an empty name. As a hack, we bump the
1578 length to 1 so that the loop will balk on the trailing \0. */
1579 if (n == 0)
1580 n = 1;
1581 for (i = 0; i < n; i++, p++) {
Walter Dörwald7815c5e2007-06-11 14:55:19 +00001582 if (i > 255 || (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_')) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001583 PyErr_SetString(PyExc_TypeError,
1584 "__slots__ must be identifiers");
1585 return 0;
1586 }
1587 }
1588 return 1;
1589}
1590
Guido van Rossumd8faa362007-04-27 19:54:29 +00001591/* Forward */
1592static int
1593object_init(PyObject *self, PyObject *args, PyObject *kwds);
1594
1595static int
1596type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1597{
1598 int res;
1599
1600 assert(args != NULL && PyTuple_Check(args));
1601 assert(kwds == NULL || PyDict_Check(kwds));
1602
1603 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1604 PyErr_SetString(PyExc_TypeError,
1605 "type.__init__() takes no keyword arguments");
1606 return -1;
1607 }
1608
1609 if (args != NULL && PyTuple_Check(args) &&
1610 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1611 PyErr_SetString(PyExc_TypeError,
1612 "type.__init__() takes 1 or 3 arguments");
1613 return -1;
1614 }
1615
1616 /* Call object.__init__(self) now. */
1617 /* XXX Could call super(type, cls).__init__() but what's the point? */
1618 args = PyTuple_GetSlice(args, 0, 0);
1619 res = object_init(cls, args, NULL);
1620 Py_DECREF(args);
1621 return res;
1622}
1623
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001624static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001625type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1626{
1627 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001628 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001629 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001630 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001631 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001632 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001633 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001634 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001635
Tim Peters3abca122001-10-27 19:37:48 +00001636 assert(args != NULL && PyTuple_Check(args));
1637 assert(kwds == NULL || PyDict_Check(kwds));
1638
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001639 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001640 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001641 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1642 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001643
1644 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1645 PyObject *x = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001646 Py_INCREF(Py_Type(x));
1647 return (PyObject *) Py_Type(x);
Tim Peters3abca122001-10-27 19:37:48 +00001648 }
1649
1650 /* SF bug 475327 -- if that didn't trigger, we need 3
1651 arguments. but PyArg_ParseTupleAndKeywords below may give
1652 a msg saying type() needs exactly 3. */
1653 if (nargs + nkwds != 3) {
1654 PyErr_SetString(PyExc_TypeError,
1655 "type() takes 1 or 3 arguments");
1656 return NULL;
1657 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001658 }
1659
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001660 /* Check arguments: (name, bases, dict) */
Thomas Hellerace8ba82007-07-11 20:01:43 +00001661 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001662 &name,
1663 &PyTuple_Type, &bases,
1664 &PyDict_Type, &dict))
1665 return NULL;
1666
1667 /* Determine the proper metatype to deal with this,
1668 and check for metatype conflicts while we're at it.
1669 Note that if some other metatype wins to contract,
1670 it's possible that its instances are not types. */
1671 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001672 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001673 for (i = 0; i < nbases; i++) {
1674 tmp = PyTuple_GET_ITEM(bases, i);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001675 tmptype = Py_Type(tmp);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001676 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001678 if (PyType_IsSubtype(tmptype, winner)) {
1679 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001680 continue;
1681 }
1682 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001683 "metaclass conflict: "
1684 "the metaclass of a derived class "
1685 "must be a (non-strict) subclass "
1686 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001687 return NULL;
1688 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001689 if (winner != metatype) {
1690 if (winner->tp_new != type_new) /* Pass it to the winner */
1691 return winner->tp_new(winner, args, kwds);
1692 metatype = winner;
1693 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001694
1695 /* Adjust for empty tuple bases */
1696 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001697 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 if (bases == NULL)
1699 return NULL;
1700 nbases = 1;
1701 }
1702 else
1703 Py_INCREF(bases);
1704
1705 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1706
1707 /* Calculate best base, and check that all bases are type objects */
1708 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001709 if (base == NULL) {
1710 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001711 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001712 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001713 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1714 PyErr_Format(PyExc_TypeError,
1715 "type '%.100s' is not an acceptable base type",
1716 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001717 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718 return NULL;
1719 }
1720
Tim Peters6d6c1a32001-08-02 04:15:00 +00001721 /* Check for a __slots__ sequence variable in dict, and count it */
1722 slots = PyDict_GetItemString(dict, "__slots__");
1723 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001724 add_dict = 0;
1725 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001726 may_add_dict = base->tp_dictoffset == 0;
1727 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1728 if (slots == NULL) {
1729 if (may_add_dict) {
1730 add_dict++;
1731 }
1732 if (may_add_weak) {
1733 add_weak++;
1734 }
1735 }
1736 else {
1737 /* Have slots */
1738
Tim Peters6d6c1a32001-08-02 04:15:00 +00001739 /* Make it into a tuple */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001740 if (PyString_Check(slots) || PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001741 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001742 else
1743 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001744 if (slots == NULL) {
1745 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001746 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001747 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001748 assert(PyTuple_Check(slots));
1749
1750 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001752 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001753 PyErr_Format(PyExc_TypeError,
1754 "nonempty __slots__ "
1755 "not supported for subtype of '%s'",
1756 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001757 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001758 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001759 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001760 return NULL;
1761 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001762
1763 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001764 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001765 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001766 if (!valid_identifier(tmp))
1767 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001768 assert(PyUnicode_Check(tmp));
1769 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001770 if (!may_add_dict || add_dict) {
1771 PyErr_SetString(PyExc_TypeError,
1772 "__dict__ slot disallowed: "
1773 "we already got one");
1774 goto bad_slots;
1775 }
1776 add_dict++;
1777 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001778 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001779 if (!may_add_weak || add_weak) {
1780 PyErr_SetString(PyExc_TypeError,
1781 "__weakref__ slot disallowed: "
1782 "either we already got one, "
1783 "or __itemsize__ != 0");
1784 goto bad_slots;
1785 }
1786 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001787 }
1788 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001789
Guido van Rossumd8faa362007-04-27 19:54:29 +00001790 /* Copy slots into a list, mangle names and sort them.
1791 Sorted names are needed for __class__ assignment.
1792 Convert them back to tuple at the end.
1793 */
1794 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001795 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001796 goto bad_slots;
1797 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001798 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001799 if ((add_dict &&
1800 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
1801 (add_weak &&
1802 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00001803 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001805 if (!tmp)
1806 goto bad_slots;
1807 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001808 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001809 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001810 assert(j == nslots - add_dict - add_weak);
1811 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001812 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001813 if (PyList_Sort(newslots) == -1) {
1814 Py_DECREF(bases);
1815 Py_DECREF(newslots);
1816 return NULL;
1817 }
1818 slots = PyList_AsTuple(newslots);
1819 Py_DECREF(newslots);
1820 if (slots == NULL) {
1821 Py_DECREF(bases);
1822 return NULL;
1823 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001824
Guido van Rossumad47da02002-08-12 19:05:44 +00001825 /* Secondary bases may provide weakrefs or dict */
1826 if (nbases > 1 &&
1827 ((may_add_dict && !add_dict) ||
1828 (may_add_weak && !add_weak))) {
1829 for (i = 0; i < nbases; i++) {
1830 tmp = PyTuple_GET_ITEM(bases, i);
1831 if (tmp == (PyObject *)base)
1832 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001833 assert(PyType_Check(tmp));
1834 tmptype = (PyTypeObject *)tmp;
1835 if (may_add_dict && !add_dict &&
1836 tmptype->tp_dictoffset != 0)
1837 add_dict++;
1838 if (may_add_weak && !add_weak &&
1839 tmptype->tp_weaklistoffset != 0)
1840 add_weak++;
1841 if (may_add_dict && !add_dict)
1842 continue;
1843 if (may_add_weak && !add_weak)
1844 continue;
1845 /* Nothing more to check */
1846 break;
1847 }
1848 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001849 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001850
1851 /* XXX From here until type is safely allocated,
1852 "return NULL" may leak slots! */
1853
1854 /* Allocate the type object */
1855 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001856 if (type == NULL) {
1857 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001858 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001859 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001860 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001861
1862 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001863 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001864 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001865 et->ht_name = name;
1866 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001867
Guido van Rossumdc91b992001-08-08 22:26:22 +00001868 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001869 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1870 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001871 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1872 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001873
Guido van Rossumdc91b992001-08-08 22:26:22 +00001874 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001875 type->tp_as_number = &et->as_number;
1876 type->tp_as_sequence = &et->as_sequence;
1877 type->tp_as_mapping = &et->as_mapping;
1878 type->tp_as_buffer = &et->as_buffer;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001879 if (PyString_Check(name))
1880 type->tp_name = PyString_AsString(name);
1881 else {
1882 type->tp_name = PyUnicode_AsString(name);
1883 if (!type->tp_name) {
1884 Py_DECREF(type);
1885 return NULL;
1886 }
1887 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001888
1889 /* Set tp_base and tp_bases */
1890 type->tp_bases = bases;
1891 Py_INCREF(base);
1892 type->tp_base = base;
1893
Guido van Rossum687ae002001-10-15 22:03:32 +00001894 /* Initialize tp_dict from passed-in dict */
1895 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896 if (dict == NULL) {
1897 Py_DECREF(type);
1898 return NULL;
1899 }
1900
Guido van Rossumc3542212001-08-16 09:18:56 +00001901 /* Set __module__ in the dict */
1902 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1903 tmp = PyEval_GetGlobals();
1904 if (tmp != NULL) {
1905 tmp = PyDict_GetItemString(tmp, "__name__");
1906 if (tmp != NULL) {
1907 if (PyDict_SetItemString(dict, "__module__",
1908 tmp) < 0)
1909 return NULL;
1910 }
1911 }
1912 }
1913
Tim Peters2f93e282001-10-04 05:27:00 +00001914 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001915 and is a string. The __doc__ accessor will first look for tp_doc;
1916 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001917 */
1918 {
1919 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1920 if (doc != NULL && PyString_Check(doc)) {
1921 const size_t n = (size_t)PyString_GET_SIZE(doc);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001922 char *tp_doc = (char *)PyObject_MALLOC(n+1);
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001923 if (tp_doc == NULL) {
Tim Peters2f93e282001-10-04 05:27:00 +00001924 Py_DECREF(type);
1925 return NULL;
1926 }
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001927 memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001928 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001929 }
1930 }
1931
Tim Peters6d6c1a32001-08-02 04:15:00 +00001932 /* Special-case __new__: if it's a plain function,
1933 make it a static function */
1934 tmp = PyDict_GetItemString(dict, "__new__");
1935 if (tmp != NULL && PyFunction_Check(tmp)) {
1936 tmp = PyStaticMethod_New(tmp);
1937 if (tmp == NULL) {
1938 Py_DECREF(type);
1939 return NULL;
1940 }
1941 PyDict_SetItemString(dict, "__new__", tmp);
1942 Py_DECREF(tmp);
1943 }
1944
1945 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001946 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001947 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001948 if (slots != NULL) {
1949 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001950 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00001951 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001952 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001953 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001954
1955 /* __dict__ and __weakref__ are already filtered out */
1956 assert(strcmp(mp->name, "__dict__") != 0);
1957 assert(strcmp(mp->name, "__weakref__") != 0);
1958
Tim Peters6d6c1a32001-08-02 04:15:00 +00001959 slotoffset += sizeof(PyObject *);
1960 }
1961 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001962 if (add_dict) {
1963 if (base->tp_itemsize)
1964 type->tp_dictoffset = -(long)sizeof(PyObject *);
1965 else
1966 type->tp_dictoffset = slotoffset;
1967 slotoffset += sizeof(PyObject *);
1968 }
1969 if (add_weak) {
1970 assert(!base->tp_itemsize);
1971 type->tp_weaklistoffset = slotoffset;
1972 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001973 }
1974 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001975 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001976 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001977
1978 if (type->tp_weaklistoffset && type->tp_dictoffset)
1979 type->tp_getset = subtype_getsets_full;
1980 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1981 type->tp_getset = subtype_getsets_weakref_only;
1982 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1983 type->tp_getset = subtype_getsets_dict_only;
1984 else
1985 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001986
1987 /* Special case some slots */
1988 if (type->tp_dictoffset != 0 || nslots > 0) {
1989 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1990 type->tp_getattro = PyObject_GenericGetAttr;
1991 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1992 type->tp_setattro = PyObject_GenericSetAttr;
1993 }
1994 type->tp_dealloc = subtype_dealloc;
1995
Guido van Rossum9475a232001-10-05 20:51:39 +00001996 /* Enable GC unless there are really no instance variables possible */
1997 if (!(type->tp_basicsize == sizeof(PyObject) &&
1998 type->tp_itemsize == 0))
1999 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2000
Tim Peters6d6c1a32001-08-02 04:15:00 +00002001 /* Always override allocation strategy to use regular heap */
2002 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00002003 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002004 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00002005 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00002006 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00002007 }
2008 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00002009 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010
2011 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002012 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002013 Py_DECREF(type);
2014 return NULL;
2015 }
2016
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002017 /* Put the proper slots in place */
2018 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002019
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020 return (PyObject *)type;
2021}
2022
2023/* Internal API to look for a name through the MRO.
2024 This returns a borrowed reference, and doesn't set an exception! */
2025PyObject *
2026_PyType_Lookup(PyTypeObject *type, PyObject *name)
2027{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002028 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002029 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030
Guido van Rossum687ae002001-10-15 22:03:32 +00002031 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002032 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002033
2034 /* If mro is NULL, the type is either not yet initialized
2035 by PyType_Ready(), or already cleared by type_clear().
2036 Either way the safest thing to do is to return NULL. */
2037 if (mro == NULL)
2038 return NULL;
2039
Tim Peters6d6c1a32001-08-02 04:15:00 +00002040 assert(PyTuple_Check(mro));
2041 n = PyTuple_GET_SIZE(mro);
2042 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002043 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002044 assert(PyType_Check(base));
2045 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002046 assert(dict && PyDict_Check(dict));
2047 res = PyDict_GetItem(dict, name);
2048 if (res != NULL)
2049 return res;
2050 }
2051 return NULL;
2052}
2053
2054/* This is similar to PyObject_GenericGetAttr(),
2055 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2056static PyObject *
2057type_getattro(PyTypeObject *type, PyObject *name)
2058{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002059 PyTypeObject *metatype = Py_Type(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002060 PyObject *meta_attribute, *attribute;
2061 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002062
2063 /* Initialize this type (we'll assume the metatype is initialized) */
2064 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002065 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002066 return NULL;
2067 }
2068
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002069 /* No readable descriptor found yet */
2070 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002071
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002072 /* Look for the attribute in the metatype */
2073 meta_attribute = _PyType_Lookup(metatype, name);
2074
2075 if (meta_attribute != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002076 meta_get = Py_Type(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002077
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002078 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2079 /* Data descriptors implement tp_descr_set to intercept
2080 * writes. Assume the attribute is not overridden in
2081 * type's tp_dict (and bases): call the descriptor now.
2082 */
2083 return meta_get(meta_attribute, (PyObject *)type,
2084 (PyObject *)metatype);
2085 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002086 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002087 }
2088
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002089 /* No data descriptor found on metatype. Look in tp_dict of this
2090 * type and its bases */
2091 attribute = _PyType_Lookup(type, name);
2092 if (attribute != NULL) {
2093 /* Implement descriptor functionality, if any */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002094 descrgetfunc local_get = Py_Type(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002095
2096 Py_XDECREF(meta_attribute);
2097
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002098 if (local_get != NULL) {
2099 /* NULL 2nd argument indicates the descriptor was
2100 * found on the target object itself (or a base) */
2101 return local_get(attribute, (PyObject *)NULL,
2102 (PyObject *)type);
2103 }
Tim Peters34592512002-07-11 06:23:50 +00002104
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002105 Py_INCREF(attribute);
2106 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002107 }
2108
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002109 /* No attribute found in local __dict__ (or bases): use the
2110 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002111 if (meta_get != NULL) {
2112 PyObject *res;
2113 res = meta_get(meta_attribute, (PyObject *)type,
2114 (PyObject *)metatype);
2115 Py_DECREF(meta_attribute);
2116 return res;
2117 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002118
2119 /* If an ordinary attribute was found on the metatype, return it now */
2120 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002121 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002122 }
2123
2124 /* Give up */
2125 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002126 "type object '%.50s' has no attribute '%U'",
2127 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002128 return NULL;
2129}
2130
2131static int
2132type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2133{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002134 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2135 PyErr_Format(
2136 PyExc_TypeError,
2137 "can't set attributes of built-in/extension type '%s'",
2138 type->tp_name);
2139 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002140 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002141 /* XXX Example of how I expect this to be used...
2142 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2143 return -1;
2144 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002145 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2146 return -1;
2147 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002148}
2149
2150static void
2151type_dealloc(PyTypeObject *type)
2152{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002153 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002154
2155 /* Assert this is a heap-allocated type object */
2156 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002157 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002158 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002159 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002160 Py_XDECREF(type->tp_base);
2161 Py_XDECREF(type->tp_dict);
2162 Py_XDECREF(type->tp_bases);
2163 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002164 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002165 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002166 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2167 * of most other objects. It's okay to cast it to char *.
2168 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002169 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002170 Py_XDECREF(et->ht_name);
2171 Py_XDECREF(et->ht_slots);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002172 Py_Type(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002173}
2174
Guido van Rossum1c450732001-10-08 15:18:27 +00002175static PyObject *
2176type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2177{
2178 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002179 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002180
2181 list = PyList_New(0);
2182 if (list == NULL)
2183 return NULL;
2184 raw = type->tp_subclasses;
2185 if (raw == NULL)
2186 return list;
2187 assert(PyList_Check(raw));
2188 n = PyList_GET_SIZE(raw);
2189 for (i = 0; i < n; i++) {
2190 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002191 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002192 ref = PyWeakref_GET_OBJECT(ref);
2193 if (ref != Py_None) {
2194 if (PyList_Append(list, ref) < 0) {
2195 Py_DECREF(list);
2196 return NULL;
2197 }
2198 }
2199 }
2200 return list;
2201}
2202
Tim Peters6d6c1a32001-08-02 04:15:00 +00002203static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002204 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002205 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002206 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002207 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002208 {0}
2209};
2210
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002211PyDoc_STRVAR(type_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002212"type(object) -> the object's type\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002213"type(name, bases, dict) -> a new type");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002214
Guido van Rossum048eb752001-10-02 21:24:57 +00002215static int
2216type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2217{
Guido van Rossuma3862092002-06-10 15:24:42 +00002218 /* Because of type_is_gc(), the collector only calls this
2219 for heaptypes. */
2220 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002221
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002222 Py_VISIT(type->tp_dict);
2223 Py_VISIT(type->tp_cache);
2224 Py_VISIT(type->tp_mro);
2225 Py_VISIT(type->tp_bases);
2226 Py_VISIT(type->tp_base);
Guido van Rossuma3862092002-06-10 15:24:42 +00002227
2228 /* There's no need to visit type->tp_subclasses or
Georg Brandlc255c7b2006-02-20 22:27:28 +00002229 ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
Guido van Rossuma3862092002-06-10 15:24:42 +00002230 in cycles; tp_subclasses is a list of weak references,
2231 and slots is a tuple of strings. */
Guido van Rossum048eb752001-10-02 21:24:57 +00002232
Guido van Rossum048eb752001-10-02 21:24:57 +00002233 return 0;
2234}
2235
2236static int
2237type_clear(PyTypeObject *type)
2238{
Guido van Rossuma3862092002-06-10 15:24:42 +00002239 /* Because of type_is_gc(), the collector only calls this
2240 for heaptypes. */
2241 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002242
Guido van Rossuma3862092002-06-10 15:24:42 +00002243 /* The only field we need to clear is tp_mro, which is part of a
2244 hard cycle (its first element is the class itself) that won't
2245 be broken otherwise (it's a tuple and tuples don't have a
2246 tp_clear handler). None of the other fields need to be
2247 cleared, and here's why:
Guido van Rossum048eb752001-10-02 21:24:57 +00002248
Guido van Rossuma3862092002-06-10 15:24:42 +00002249 tp_dict:
2250 It is a dict, so the collector will call its tp_clear.
2251
2252 tp_cache:
2253 Not used; if it were, it would be a dict.
2254
2255 tp_bases, tp_base:
2256 If these are involved in a cycle, there must be at least
2257 one other, mutable object in the cycle, e.g. a base
2258 class's dict; the cycle will be broken that way.
2259
2260 tp_subclasses:
2261 A list of weak references can't be part of a cycle; and
2262 lists have their own tp_clear.
2263
Guido van Rossume5c691a2003-03-07 15:13:17 +00002264 slots (in PyHeapTypeObject):
Guido van Rossuma3862092002-06-10 15:24:42 +00002265 A tuple of strings can't be part of a cycle.
2266 */
2267
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002268 Py_CLEAR(type->tp_mro);
Guido van Rossum048eb752001-10-02 21:24:57 +00002269
2270 return 0;
2271}
2272
2273static int
2274type_is_gc(PyTypeObject *type)
2275{
2276 return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2277}
2278
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279PyTypeObject PyType_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002280 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002281 "type", /* tp_name */
Guido van Rossume5c691a2003-03-07 15:13:17 +00002282 sizeof(PyHeapTypeObject), /* tp_basicsize */
Guido van Rossum6f799372001-09-20 20:46:19 +00002283 sizeof(PyMemberDef), /* tp_itemsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002284 (destructor)type_dealloc, /* tp_dealloc */
2285 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002286 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002287 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002288 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002289 (reprfunc)type_repr, /* tp_repr */
2290 0, /* tp_as_number */
2291 0, /* tp_as_sequence */
2292 0, /* tp_as_mapping */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002293 0, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002294 (ternaryfunc)type_call, /* tp_call */
2295 0, /* tp_str */
2296 (getattrofunc)type_getattro, /* tp_getattro */
2297 (setattrofunc)type_setattro, /* tp_setattro */
2298 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00002299 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002300 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301 type_doc, /* tp_doc */
Guido van Rossum048eb752001-10-02 21:24:57 +00002302 (traverseproc)type_traverse, /* tp_traverse */
2303 (inquiry)type_clear, /* tp_clear */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304 0, /* tp_richcompare */
Guido van Rossum1c450732001-10-08 15:18:27 +00002305 offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306 0, /* tp_iter */
2307 0, /* tp_iternext */
2308 type_methods, /* tp_methods */
2309 type_members, /* tp_members */
2310 type_getsets, /* tp_getset */
2311 0, /* tp_base */
2312 0, /* tp_dict */
2313 0, /* tp_descr_get */
2314 0, /* tp_descr_set */
2315 offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002316 type_init, /* tp_init */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002317 0, /* tp_alloc */
2318 type_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002319 PyObject_GC_Del, /* tp_free */
Guido van Rossum048eb752001-10-02 21:24:57 +00002320 (inquiry)type_is_gc, /* tp_is_gc */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002321};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322
2323
2324/* The base type of all types (eventually)... except itself. */
2325
Guido van Rossumd8faa362007-04-27 19:54:29 +00002326/* You may wonder why object.__new__() only complains about arguments
2327 when object.__init__() is not overridden, and vice versa.
2328
2329 Consider the use cases:
2330
2331 1. When neither is overridden, we want to hear complaints about
2332 excess (i.e., any) arguments, since their presence could
2333 indicate there's a bug.
2334
2335 2. When defining an Immutable type, we are likely to override only
2336 __new__(), since __init__() is called too late to initialize an
2337 Immutable object. Since __new__() defines the signature for the
2338 type, it would be a pain to have to override __init__() just to
2339 stop it from complaining about excess arguments.
2340
2341 3. When defining a Mutable type, we are likely to override only
2342 __init__(). So here the converse reasoning applies: we don't
2343 want to have to override __new__() just to stop it from
2344 complaining.
2345
2346 4. When __init__() is overridden, and the subclass __init__() calls
2347 object.__init__(), the latter should complain about excess
2348 arguments; ditto for __new__().
2349
2350 Use cases 2 and 3 make it unattractive to unconditionally check for
2351 excess arguments. The best solution that addresses all four use
2352 cases is as follows: __init__() complains about excess arguments
2353 unless __new__() is overridden and __init__() is not overridden
2354 (IOW, if __init__() is overridden or __new__() is not overridden);
2355 symmetrically, __new__() complains about excess arguments unless
2356 __init__() is overridden and __new__() is not overridden
2357 (IOW, if __new__() is overridden or __init__() is not overridden).
2358
2359 However, for backwards compatibility, this breaks too much code.
2360 Therefore, in 2.6, we'll *warn* about excess arguments when both
2361 methods are overridden; for all other cases we'll use the above
2362 rules.
2363
2364*/
2365
2366/* Forward */
2367static PyObject *
2368object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
2369
2370static int
2371excess_args(PyObject *args, PyObject *kwds)
2372{
2373 return PyTuple_GET_SIZE(args) ||
2374 (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
2375}
2376
Tim Peters6d6c1a32001-08-02 04:15:00 +00002377static int
2378object_init(PyObject *self, PyObject *args, PyObject *kwds)
2379{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002380 int err = 0;
2381 if (excess_args(args, kwds)) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002382 PyTypeObject *type = Py_Type(self);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002383 if (type->tp_init != object_init &&
2384 type->tp_new != object_new)
2385 {
2386 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2387 "object.__init__() takes no parameters",
2388 1);
2389 }
2390 else if (type->tp_init != object_init ||
2391 type->tp_new == object_new)
2392 {
2393 PyErr_SetString(PyExc_TypeError,
2394 "object.__init__() takes no parameters");
2395 err = -1;
2396 }
2397 }
2398 return err;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002399}
2400
Guido van Rossum298e4212003-02-13 16:30:16 +00002401static PyObject *
2402object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2403{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002404 int err = 0;
2405 if (excess_args(args, kwds)) {
2406 if (type->tp_new != object_new &&
2407 type->tp_init != object_init)
2408 {
2409 err = PyErr_WarnEx(PyExc_DeprecationWarning,
2410 "object.__new__() takes no parameters",
2411 1);
2412 }
2413 else if (type->tp_new != object_new ||
2414 type->tp_init == object_init)
2415 {
2416 PyErr_SetString(PyExc_TypeError,
2417 "object.__new__() takes no parameters");
2418 err = -1;
2419 }
Guido van Rossum298e4212003-02-13 16:30:16 +00002420 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002421 if (err < 0)
2422 return NULL;
Guido van Rossum298e4212003-02-13 16:30:16 +00002423 return type->tp_alloc(type, 0);
2424}
2425
Tim Peters6d6c1a32001-08-02 04:15:00 +00002426static void
2427object_dealloc(PyObject *self)
2428{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002429 Py_Type(self)->tp_free(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002430}
2431
Guido van Rossum8e248182001-08-12 05:17:56 +00002432static PyObject *
2433object_repr(PyObject *self)
2434{
Guido van Rossum76e69632001-08-16 18:52:43 +00002435 PyTypeObject *type;
Barry Warsaw7ce36942001-08-24 18:34:26 +00002436 PyObject *mod, *name, *rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002437
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002438 type = Py_Type(self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002439 mod = type_module(type, NULL);
2440 if (mod == NULL)
2441 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +00002442 else if (!PyUnicode_Check(mod)) {
Guido van Rossum76e69632001-08-16 18:52:43 +00002443 Py_DECREF(mod);
2444 mod = NULL;
2445 }
2446 name = type_name(type, NULL);
2447 if (name == NULL)
2448 return NULL;
Walter Dörwald4dbd01b2007-06-11 14:03:45 +00002449 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "__builtin__"))
2450 rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002451 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00002452 rtn = PyUnicode_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +00002453 type->tp_name, self);
Guido van Rossum76e69632001-08-16 18:52:43 +00002454 Py_XDECREF(mod);
2455 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +00002456 return rtn;
Guido van Rossum8e248182001-08-12 05:17:56 +00002457}
2458
Guido van Rossumb8f63662001-08-15 23:57:02 +00002459static PyObject *
2460object_str(PyObject *self)
2461{
2462 unaryfunc f;
2463
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002464 f = Py_Type(self)->tp_repr;
Guido van Rossumb8f63662001-08-15 23:57:02 +00002465 if (f == NULL)
2466 f = object_repr;
2467 return f(self);
2468}
2469
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002470static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002471object_richcompare(PyObject *self, PyObject *other, int op)
2472{
2473 PyObject *res;
2474
2475 switch (op) {
2476
2477 case Py_EQ:
2478 res = (self == other) ? Py_True : Py_False;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002479 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002480 break;
2481
2482 case Py_NE:
Guido van Rossume27dc722007-03-27 22:37:34 +00002483 /* By default, != returns the opposite of ==,
2484 unless the latter returns NotImplemented. */
2485 res = PyObject_RichCompare(self, other, Py_EQ);
2486 if (res != NULL && res != Py_NotImplemented) {
2487 int ok = PyObject_IsTrue(res);
2488 Py_DECREF(res);
2489 if (ok < 0)
2490 res = NULL;
2491 else {
2492 if (ok)
2493 res = Py_False;
2494 else
2495 res = Py_True;
2496 Py_INCREF(res);
2497 }
2498 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002499 break;
2500
2501 default:
2502 res = Py_NotImplemented;
Guido van Rossum6b18a5b2007-03-29 20:49:57 +00002503 Py_INCREF(res);
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002504 break;
2505 }
2506
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002507 return res;
2508}
2509
2510static PyObject *
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002511object_get_class(PyObject *self, void *closure)
2512{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002513 Py_INCREF(Py_Type(self));
2514 return (PyObject *)(Py_Type(self));
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002515}
2516
2517static int
2518equiv_structs(PyTypeObject *a, PyTypeObject *b)
2519{
2520 return a == b ||
2521 (a != NULL &&
2522 b != NULL &&
2523 a->tp_basicsize == b->tp_basicsize &&
2524 a->tp_itemsize == b->tp_itemsize &&
2525 a->tp_dictoffset == b->tp_dictoffset &&
2526 a->tp_weaklistoffset == b->tp_weaklistoffset &&
2527 ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2528 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2529}
2530
2531static int
2532same_slots_added(PyTypeObject *a, PyTypeObject *b)
2533{
2534 PyTypeObject *base = a->tp_base;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002535 Py_ssize_t size;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002536 PyObject *slots_a, *slots_b;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002537
2538 if (base != b->tp_base)
2539 return 0;
2540 if (equiv_structs(a, base) && equiv_structs(b, base))
2541 return 1;
2542 size = base->tp_basicsize;
2543 if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2544 size += sizeof(PyObject *);
2545 if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2546 size += sizeof(PyObject *);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002547
2548 /* Check slots compliance */
2549 slots_a = ((PyHeapTypeObject *)a)->ht_slots;
2550 slots_b = ((PyHeapTypeObject *)b)->ht_slots;
2551 if (slots_a && slots_b) {
2552 if (PyObject_Compare(slots_a, slots_b) != 0)
2553 return 0;
2554 size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
2555 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002556 return size == a->tp_basicsize && size == b->tp_basicsize;
2557}
2558
2559static int
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002560compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002561{
2562 PyTypeObject *newbase, *oldbase;
2563
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002564 if (newto->tp_dealloc != oldto->tp_dealloc ||
2565 newto->tp_free != oldto->tp_free)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002566 {
2567 PyErr_Format(PyExc_TypeError,
2568 "%s assignment: "
2569 "'%s' deallocator differs from '%s'",
2570 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002571 newto->tp_name,
2572 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002573 return 0;
2574 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002575 newbase = newto;
2576 oldbase = oldto;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002577 while (equiv_structs(newbase, newbase->tp_base))
2578 newbase = newbase->tp_base;
2579 while (equiv_structs(oldbase, oldbase->tp_base))
2580 oldbase = oldbase->tp_base;
2581 if (newbase != oldbase &&
2582 (newbase->tp_base != oldbase->tp_base ||
2583 !same_slots_added(newbase, oldbase))) {
2584 PyErr_Format(PyExc_TypeError,
2585 "%s assignment: "
2586 "'%s' object layout differs from '%s'",
2587 attr,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002588 newto->tp_name,
2589 oldto->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002590 return 0;
2591 }
Tim Petersea7f75d2002-12-07 21:39:16 +00002592
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002593 return 1;
2594}
2595
2596static int
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002597object_set_class(PyObject *self, PyObject *value, void *closure)
2598{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002599 PyTypeObject *oldto = Py_Type(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002600 PyTypeObject *newto;
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002601
Guido van Rossumb6b89422002-04-15 01:03:30 +00002602 if (value == NULL) {
2603 PyErr_SetString(PyExc_TypeError,
2604 "can't delete __class__ attribute");
2605 return -1;
2606 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002607 if (!PyType_Check(value)) {
2608 PyErr_Format(PyExc_TypeError,
2609 "__class__ must be set to new-style class, not '%s' object",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002610 Py_Type(value)->tp_name);
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002611 return -1;
2612 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002613 newto = (PyTypeObject *)value;
2614 if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2615 !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
Guido van Rossum40af8892002-08-10 05:42:07 +00002616 {
2617 PyErr_Format(PyExc_TypeError,
2618 "__class__ assignment: only for heap types");
2619 return -1;
2620 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002621 if (compatible_for_assignment(newto, oldto, "__class__")) {
2622 Py_INCREF(newto);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002623 Py_Type(self) = newto;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002624 Py_DECREF(oldto);
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002625 return 0;
2626 }
2627 else {
Guido van Rossum9ee4b942002-05-24 18:47:47 +00002628 return -1;
2629 }
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002630}
2631
2632static PyGetSetDef object_getsets[] = {
2633 {"__class__", object_get_class, object_set_class,
Neal Norwitz858e34f2002-08-13 17:18:45 +00002634 PyDoc_STR("the object's class")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00002635 {0}
2636};
2637
Guido van Rossumc53f0092003-02-18 22:05:12 +00002638
Guido van Rossum036f9992003-02-21 22:02:54 +00002639/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2640 We fall back to helpers in copy_reg for:
2641 - pickle protocols < 2
2642 - calculating the list of slot names (done only once per class)
2643 - the __newobj__ function (which is used as a token but never called)
2644*/
2645
2646static PyObject *
2647import_copy_reg(void)
2648{
2649 static PyObject *copy_reg_str;
Guido van Rossum3926a632001-09-25 16:25:58 +00002650
2651 if (!copy_reg_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002652 copy_reg_str = PyUnicode_InternFromString("copy_reg");
Guido van Rossum3926a632001-09-25 16:25:58 +00002653 if (copy_reg_str == NULL)
2654 return NULL;
2655 }
Guido van Rossum036f9992003-02-21 22:02:54 +00002656
2657 return PyImport_Import(copy_reg_str);
2658}
2659
2660static PyObject *
2661slotnames(PyObject *cls)
2662{
2663 PyObject *clsdict;
2664 PyObject *copy_reg;
2665 PyObject *slotnames;
2666
2667 if (!PyType_Check(cls)) {
2668 Py_INCREF(Py_None);
2669 return Py_None;
2670 }
2671
2672 clsdict = ((PyTypeObject *)cls)->tp_dict;
2673 slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
Armin Rigoec862b92005-09-24 22:58:41 +00002674 if (slotnames != NULL && PyList_Check(slotnames)) {
Guido van Rossum036f9992003-02-21 22:02:54 +00002675 Py_INCREF(slotnames);
2676 return slotnames;
2677 }
2678
2679 copy_reg = import_copy_reg();
2680 if (copy_reg == NULL)
2681 return NULL;
2682
2683 slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2684 Py_DECREF(copy_reg);
2685 if (slotnames != NULL &&
2686 slotnames != Py_None &&
2687 !PyList_Check(slotnames))
2688 {
2689 PyErr_SetString(PyExc_TypeError,
2690 "copy_reg._slotnames didn't return a list or None");
2691 Py_DECREF(slotnames);
2692 slotnames = NULL;
2693 }
2694
2695 return slotnames;
2696}
2697
2698static PyObject *
2699reduce_2(PyObject *obj)
2700{
2701 PyObject *cls, *getnewargs;
2702 PyObject *args = NULL, *args2 = NULL;
2703 PyObject *getstate = NULL, *state = NULL, *names = NULL;
2704 PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2705 PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002706 Py_ssize_t i, n;
Guido van Rossum036f9992003-02-21 22:02:54 +00002707
2708 cls = PyObject_GetAttrString(obj, "__class__");
2709 if (cls == NULL)
2710 return NULL;
2711
2712 getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2713 if (getnewargs != NULL) {
2714 args = PyObject_CallObject(getnewargs, NULL);
2715 Py_DECREF(getnewargs);
2716 if (args != NULL && !PyTuple_Check(args)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002717 PyErr_Format(PyExc_TypeError,
2718 "__getnewargs__ should return a tuple, "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002719 "not '%.200s'", Py_Type(args)->tp_name);
Guido van Rossum036f9992003-02-21 22:02:54 +00002720 goto end;
2721 }
2722 }
2723 else {
2724 PyErr_Clear();
2725 args = PyTuple_New(0);
2726 }
2727 if (args == NULL)
2728 goto end;
2729
2730 getstate = PyObject_GetAttrString(obj, "__getstate__");
2731 if (getstate != NULL) {
2732 state = PyObject_CallObject(getstate, NULL);
2733 Py_DECREF(getstate);
Neal Norwitze2fdc612003-06-08 13:19:58 +00002734 if (state == NULL)
2735 goto end;
Guido van Rossum036f9992003-02-21 22:02:54 +00002736 }
2737 else {
Jim Fulton8a1a5942004-02-08 04:21:26 +00002738 PyErr_Clear();
Guido van Rossum036f9992003-02-21 22:02:54 +00002739 state = PyObject_GetAttrString(obj, "__dict__");
2740 if (state == NULL) {
2741 PyErr_Clear();
2742 state = Py_None;
2743 Py_INCREF(state);
2744 }
2745 names = slotnames(cls);
2746 if (names == NULL)
2747 goto end;
2748 if (names != Py_None) {
2749 assert(PyList_Check(names));
2750 slots = PyDict_New();
2751 if (slots == NULL)
2752 goto end;
2753 n = 0;
2754 /* Can't pre-compute the list size; the list
2755 is stored on the class so accessible to other
2756 threads, which may be run by DECREF */
2757 for (i = 0; i < PyList_GET_SIZE(names); i++) {
2758 PyObject *name, *value;
2759 name = PyList_GET_ITEM(names, i);
2760 value = PyObject_GetAttr(obj, name);
2761 if (value == NULL)
2762 PyErr_Clear();
2763 else {
2764 int err = PyDict_SetItem(slots, name,
2765 value);
2766 Py_DECREF(value);
2767 if (err)
2768 goto end;
2769 n++;
2770 }
2771 }
2772 if (n) {
2773 state = Py_BuildValue("(NO)", state, slots);
2774 if (state == NULL)
2775 goto end;
2776 }
2777 }
2778 }
2779
2780 if (!PyList_Check(obj)) {
2781 listitems = Py_None;
2782 Py_INCREF(listitems);
2783 }
2784 else {
2785 listitems = PyObject_GetIter(obj);
2786 if (listitems == NULL)
2787 goto end;
2788 }
2789
2790 if (!PyDict_Check(obj)) {
2791 dictitems = Py_None;
2792 Py_INCREF(dictitems);
2793 }
2794 else {
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002795 PyObject *items = PyObject_CallMethod(obj, "items", "");
2796 if (items == NULL)
2797 goto end;
2798 dictitems = PyObject_GetIter(items);
2799 Py_DECREF(items);
Guido van Rossum036f9992003-02-21 22:02:54 +00002800 if (dictitems == NULL)
2801 goto end;
2802 }
2803
2804 copy_reg = import_copy_reg();
2805 if (copy_reg == NULL)
2806 goto end;
2807 newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2808 if (newobj == NULL)
2809 goto end;
2810
2811 n = PyTuple_GET_SIZE(args);
2812 args2 = PyTuple_New(n+1);
2813 if (args2 == NULL)
2814 goto end;
2815 PyTuple_SET_ITEM(args2, 0, cls);
2816 cls = NULL;
2817 for (i = 0; i < n; i++) {
2818 PyObject *v = PyTuple_GET_ITEM(args, i);
2819 Py_INCREF(v);
2820 PyTuple_SET_ITEM(args2, i+1, v);
2821 }
2822
Raymond Hettinger8ae46892003-10-12 19:09:37 +00002823 res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
Guido van Rossum036f9992003-02-21 22:02:54 +00002824
2825 end:
2826 Py_XDECREF(cls);
2827 Py_XDECREF(args);
2828 Py_XDECREF(args2);
Jeremy Hyltond06483c2003-04-09 21:01:42 +00002829 Py_XDECREF(slots);
Guido van Rossum036f9992003-02-21 22:02:54 +00002830 Py_XDECREF(state);
2831 Py_XDECREF(names);
2832 Py_XDECREF(listitems);
2833 Py_XDECREF(dictitems);
2834 Py_XDECREF(copy_reg);
2835 Py_XDECREF(newobj);
2836 return res;
2837}
2838
Guido van Rossumd8faa362007-04-27 19:54:29 +00002839/*
2840 * There were two problems when object.__reduce__ and object.__reduce_ex__
2841 * were implemented in the same function:
2842 * - trying to pickle an object with a custom __reduce__ method that
2843 * fell back to object.__reduce__ in certain circumstances led to
2844 * infinite recursion at Python level and eventual RuntimeError.
2845 * - Pickling objects that lied about their type by overwriting the
2846 * __class__ descriptor could lead to infinite recursion at C level
2847 * and eventual segfault.
2848 *
2849 * Because of backwards compatibility, the two methods still have to
2850 * behave in the same way, even if this is not required by the pickle
2851 * protocol. This common functionality was moved to the _common_reduce
2852 * function.
2853 */
2854static PyObject *
2855_common_reduce(PyObject *self, int proto)
2856{
2857 PyObject *copy_reg, *res;
2858
2859 if (proto >= 2)
2860 return reduce_2(self);
2861
2862 copy_reg = import_copy_reg();
2863 if (!copy_reg)
2864 return NULL;
2865
2866 res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2867 Py_DECREF(copy_reg);
2868
2869 return res;
2870}
2871
2872static PyObject *
2873object_reduce(PyObject *self, PyObject *args)
2874{
2875 int proto = 0;
2876
2877 if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
2878 return NULL;
2879
2880 return _common_reduce(self, proto);
2881}
2882
Guido van Rossum036f9992003-02-21 22:02:54 +00002883static PyObject *
2884object_reduce_ex(PyObject *self, PyObject *args)
2885{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002886 PyObject *reduce, *res;
Guido van Rossum036f9992003-02-21 22:02:54 +00002887 int proto = 0;
2888
2889 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2890 return NULL;
2891
2892 reduce = PyObject_GetAttrString(self, "__reduce__");
2893 if (reduce == NULL)
2894 PyErr_Clear();
2895 else {
2896 PyObject *cls, *clsreduce, *objreduce;
2897 int override;
2898 cls = PyObject_GetAttrString(self, "__class__");
2899 if (cls == NULL) {
2900 Py_DECREF(reduce);
2901 return NULL;
2902 }
2903 clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2904 Py_DECREF(cls);
2905 if (clsreduce == NULL) {
2906 Py_DECREF(reduce);
2907 return NULL;
2908 }
2909 objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2910 "__reduce__");
2911 override = (clsreduce != objreduce);
2912 Py_DECREF(clsreduce);
2913 if (override) {
2914 res = PyObject_CallObject(reduce, NULL);
2915 Py_DECREF(reduce);
2916 return res;
2917 }
2918 else
2919 Py_DECREF(reduce);
2920 }
2921
Guido van Rossumd8faa362007-04-27 19:54:29 +00002922 return _common_reduce(self, proto);
Guido van Rossum3926a632001-09-25 16:25:58 +00002923}
2924
2925static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002926 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2927 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002928 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002929 PyDoc_STR("helper for pickle")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002930 {0}
2931};
2932
Guido van Rossum036f9992003-02-21 22:02:54 +00002933
Tim Peters6d6c1a32001-08-02 04:15:00 +00002934PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002935 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002936 "object", /* tp_name */
2937 sizeof(PyObject), /* tp_basicsize */
2938 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002939 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002940 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002941 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002942 0, /* tp_setattr */
2943 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002944 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002945 0, /* tp_as_number */
2946 0, /* tp_as_sequence */
2947 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002948 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002949 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002950 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002951 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002952 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002953 0, /* tp_as_buffer */
2954 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002955 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002956 0, /* tp_traverse */
2957 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002958 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002959 0, /* tp_weaklistoffset */
2960 0, /* tp_iter */
2961 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00002962 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00002963 0, /* tp_members */
2964 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002965 0, /* tp_base */
2966 0, /* tp_dict */
2967 0, /* tp_descr_get */
2968 0, /* tp_descr_set */
2969 0, /* tp_dictoffset */
2970 object_init, /* tp_init */
2971 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00002972 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002973 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002974};
2975
2976
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002977/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002978
2979static int
2980add_methods(PyTypeObject *type, PyMethodDef *meth)
2981{
Guido van Rossum687ae002001-10-15 22:03:32 +00002982 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983
2984 for (; meth->ml_name != NULL; meth++) {
2985 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002986 if (PyDict_GetItemString(dict, meth->ml_name) &&
2987 !(meth->ml_flags & METH_COEXIST))
2988 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00002989 if (meth->ml_flags & METH_CLASS) {
2990 if (meth->ml_flags & METH_STATIC) {
2991 PyErr_SetString(PyExc_ValueError,
2992 "method cannot be both class and static");
2993 return -1;
2994 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00002995 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00002996 }
2997 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00002998 PyObject *cfunc = PyCFunction_New(meth, NULL);
2999 if (cfunc == NULL)
3000 return -1;
3001 descr = PyStaticMethod_New(cfunc);
3002 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003003 }
3004 else {
3005 descr = PyDescr_NewMethod(type, meth);
3006 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003007 if (descr == NULL)
3008 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003009 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003010 return -1;
3011 Py_DECREF(descr);
3012 }
3013 return 0;
3014}
3015
3016static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003017add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003018{
Guido van Rossum687ae002001-10-15 22:03:32 +00003019 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003020
3021 for (; memb->name != NULL; memb++) {
3022 PyObject *descr;
3023 if (PyDict_GetItemString(dict, memb->name))
3024 continue;
3025 descr = PyDescr_NewMember(type, memb);
3026 if (descr == NULL)
3027 return -1;
3028 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3029 return -1;
3030 Py_DECREF(descr);
3031 }
3032 return 0;
3033}
3034
3035static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003036add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003037{
Guido van Rossum687ae002001-10-15 22:03:32 +00003038 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003039
3040 for (; gsp->name != NULL; gsp++) {
3041 PyObject *descr;
3042 if (PyDict_GetItemString(dict, gsp->name))
3043 continue;
3044 descr = PyDescr_NewGetSet(type, gsp);
3045
3046 if (descr == NULL)
3047 return -1;
3048 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3049 return -1;
3050 Py_DECREF(descr);
3051 }
3052 return 0;
3053}
3054
Guido van Rossum13d52f02001-08-10 21:24:08 +00003055static void
3056inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003057{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003058 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059
Guido van Rossum13d52f02001-08-10 21:24:08 +00003060 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003061 oldsize = base->tp_basicsize;
3062 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3063 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3064 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003065 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003066 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003067 if (type->tp_traverse == NULL)
3068 type->tp_traverse = base->tp_traverse;
3069 if (type->tp_clear == NULL)
3070 type->tp_clear = base->tp_clear;
3071 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003072 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003073 /* The condition below could use some explanation.
3074 It appears that tp_new is not inherited for static types
3075 whose base class is 'object'; this seems to be a precaution
3076 so that old extension types don't suddenly become
3077 callable (object.__new__ wouldn't insure the invariants
3078 that the extension type's own factory function ensures).
3079 Heap types, of course, are under our control, so they do
3080 inherit tp_new; static extension types that specify some
3081 other built-in type as the default are considered
3082 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003083 if (base != &PyBaseObject_Type ||
3084 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3085 if (type->tp_new == NULL)
3086 type->tp_new = base->tp_new;
3087 }
3088 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003089 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003090
3091 /* Copy other non-function slots */
3092
3093#undef COPYVAL
3094#define COPYVAL(SLOT) \
3095 if (type->SLOT == 0) type->SLOT = base->SLOT
3096
3097 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003098 COPYVAL(tp_weaklistoffset);
3099 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003100
3101 /* Setup fast subclass flags */
3102 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3103 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3104 else if (PyType_IsSubtype(base, &PyType_Type))
3105 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3106 else if (PyType_IsSubtype(base, &PyLong_Type))
3107 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3108 else if (PyType_IsSubtype(base, &PyString_Type))
3109 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3110 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3111 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3112 else if (PyType_IsSubtype(base, &PyTuple_Type))
3113 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3114 else if (PyType_IsSubtype(base, &PyList_Type))
3115 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3116 else if (PyType_IsSubtype(base, &PyDict_Type))
3117 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003118}
3119
Guido van Rossum38938152006-08-21 23:36:26 +00003120/* Map rich comparison operators to their __xx__ namesakes */
3121static char *name_op[] = {
3122 "__lt__",
3123 "__le__",
3124 "__eq__",
3125 "__ne__",
3126 "__gt__",
3127 "__ge__",
3128 /* These are only for overrides_cmp_or_hash(): */
3129 "__cmp__",
3130 "__hash__",
3131};
3132
3133static int
3134overrides_cmp_or_hash(PyTypeObject *type)
3135{
3136 int i;
3137 PyObject *dict = type->tp_dict;
3138
3139 assert(dict != NULL);
3140 for (i = 0; i < 8; i++) {
3141 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
3142 return 1;
3143 }
3144 return 0;
3145}
3146
Guido van Rossum13d52f02001-08-10 21:24:08 +00003147static void
3148inherit_slots(PyTypeObject *type, PyTypeObject *base)
3149{
3150 PyTypeObject *basebase;
3151
3152#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003153#undef COPYSLOT
3154#undef COPYNUM
3155#undef COPYSEQ
3156#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003157#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003158
3159#define SLOTDEFINED(SLOT) \
3160 (base->SLOT != 0 && \
3161 (basebase == NULL || base->SLOT != basebase->SLOT))
3162
Tim Peters6d6c1a32001-08-02 04:15:00 +00003163#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003164 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003165
3166#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3167#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3168#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003169#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003170
Guido van Rossum13d52f02001-08-10 21:24:08 +00003171 /* This won't inherit indirect slots (from tp_as_number etc.)
3172 if type doesn't provide the space. */
3173
3174 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3175 basebase = base->tp_base;
3176 if (basebase->tp_as_number == NULL)
3177 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003178 COPYNUM(nb_add);
3179 COPYNUM(nb_subtract);
3180 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003181 COPYNUM(nb_remainder);
3182 COPYNUM(nb_divmod);
3183 COPYNUM(nb_power);
3184 COPYNUM(nb_negative);
3185 COPYNUM(nb_positive);
3186 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003187 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003188 COPYNUM(nb_invert);
3189 COPYNUM(nb_lshift);
3190 COPYNUM(nb_rshift);
3191 COPYNUM(nb_and);
3192 COPYNUM(nb_xor);
3193 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194 COPYNUM(nb_int);
3195 COPYNUM(nb_long);
3196 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003197 COPYNUM(nb_inplace_add);
3198 COPYNUM(nb_inplace_subtract);
3199 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003200 COPYNUM(nb_inplace_remainder);
3201 COPYNUM(nb_inplace_power);
3202 COPYNUM(nb_inplace_lshift);
3203 COPYNUM(nb_inplace_rshift);
3204 COPYNUM(nb_inplace_and);
3205 COPYNUM(nb_inplace_xor);
3206 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003207 COPYNUM(nb_true_divide);
3208 COPYNUM(nb_floor_divide);
3209 COPYNUM(nb_inplace_true_divide);
3210 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003211 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003212 }
3213
Guido van Rossum13d52f02001-08-10 21:24:08 +00003214 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3215 basebase = base->tp_base;
3216 if (basebase->tp_as_sequence == NULL)
3217 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003218 COPYSEQ(sq_length);
3219 COPYSEQ(sq_concat);
3220 COPYSEQ(sq_repeat);
3221 COPYSEQ(sq_item);
3222 COPYSEQ(sq_slice);
3223 COPYSEQ(sq_ass_item);
3224 COPYSEQ(sq_ass_slice);
3225 COPYSEQ(sq_contains);
3226 COPYSEQ(sq_inplace_concat);
3227 COPYSEQ(sq_inplace_repeat);
3228 }
3229
Guido van Rossum13d52f02001-08-10 21:24:08 +00003230 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3231 basebase = base->tp_base;
3232 if (basebase->tp_as_mapping == NULL)
3233 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003234 COPYMAP(mp_length);
3235 COPYMAP(mp_subscript);
3236 COPYMAP(mp_ass_subscript);
3237 }
3238
Tim Petersfc57ccb2001-10-12 02:38:24 +00003239 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3240 basebase = base->tp_base;
3241 if (basebase->tp_as_buffer == NULL)
3242 basebase = NULL;
3243 COPYBUF(bf_getreadbuffer);
3244 COPYBUF(bf_getwritebuffer);
3245 COPYBUF(bf_getsegcount);
3246 COPYBUF(bf_getcharbuffer);
3247 }
3248
Guido van Rossum13d52f02001-08-10 21:24:08 +00003249 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003250
Tim Peters6d6c1a32001-08-02 04:15:00 +00003251 COPYSLOT(tp_dealloc);
3252 COPYSLOT(tp_print);
3253 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3254 type->tp_getattr = base->tp_getattr;
3255 type->tp_getattro = base->tp_getattro;
3256 }
3257 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3258 type->tp_setattr = base->tp_setattr;
3259 type->tp_setattro = base->tp_setattro;
3260 }
3261 /* tp_compare see tp_richcompare */
3262 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003263 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003264 COPYSLOT(tp_call);
3265 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003266 {
Guido van Rossum38938152006-08-21 23:36:26 +00003267 /* Copy comparison-related slots only when
3268 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003269 if (type->tp_compare == NULL &&
3270 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003271 type->tp_hash == NULL &&
3272 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003273 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003274 type->tp_compare = base->tp_compare;
3275 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003276 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003277 }
3278 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003279 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003280 COPYSLOT(tp_iter);
3281 COPYSLOT(tp_iternext);
3282 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003283 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003284 COPYSLOT(tp_descr_get);
3285 COPYSLOT(tp_descr_set);
3286 COPYSLOT(tp_dictoffset);
3287 COPYSLOT(tp_init);
3288 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003289 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003290 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3291 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3292 /* They agree about gc. */
3293 COPYSLOT(tp_free);
3294 }
3295 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3296 type->tp_free == NULL &&
3297 base->tp_free == _PyObject_Del) {
3298 /* A bit of magic to plug in the correct default
3299 * tp_free function when a derived class adds gc,
3300 * didn't define tp_free, and the base uses the
3301 * default non-gc tp_free.
3302 */
3303 type->tp_free = PyObject_GC_Del;
3304 }
3305 /* else they didn't agree about gc, and there isn't something
3306 * obvious to be done -- the type is on its own.
3307 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003308 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003309}
3310
Jeremy Hylton938ace62002-07-17 16:30:39 +00003311static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003312
Tim Peters6d6c1a32001-08-02 04:15:00 +00003313int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003314PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003315{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003316 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003317 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003318 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319
Guido van Rossumcab05802002-06-10 15:29:03 +00003320 if (type->tp_flags & Py_TPFLAGS_READY) {
3321 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003322 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003323 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003324 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003325
3326 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003327
Tim Peters36eb4df2003-03-23 03:33:13 +00003328#ifdef Py_TRACE_REFS
3329 /* PyType_Ready is the closest thing we have to a choke point
3330 * for type objects, so is the best place I can think of to try
3331 * to get type objects into the doubly-linked list of all objects.
3332 * Still, not all type objects go thru PyType_Ready.
3333 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003334 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003335#endif
3336
Tim Peters6d6c1a32001-08-02 04:15:00 +00003337 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3338 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003339 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003340 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003341 Py_INCREF(base);
3342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003343
Guido van Rossumd8faa362007-04-27 19:54:29 +00003344 /* Now the only way base can still be NULL is if type is
3345 * &PyBaseObject_Type.
3346 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003347
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003348 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003349 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003350 if (PyType_Ready(base) < 0)
3351 goto error;
3352 }
3353
Guido van Rossumd8faa362007-04-27 19:54:29 +00003354 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003355 compilable separately on Windows can call PyType_Ready() instead of
3356 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003357 /* The test for base != NULL is really unnecessary, since base is only
3358 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3359 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3360 know that. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003361 if (Py_Type(type) == NULL && base != NULL)
3362 Py_Type(type) = Py_Type(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003363
Tim Peters6d6c1a32001-08-02 04:15:00 +00003364 /* Initialize tp_bases */
3365 bases = type->tp_bases;
3366 if (bases == NULL) {
3367 if (base == NULL)
3368 bases = PyTuple_New(0);
3369 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003370 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003371 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003372 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003373 type->tp_bases = bases;
3374 }
3375
Guido van Rossum687ae002001-10-15 22:03:32 +00003376 /* Initialize tp_dict */
3377 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003378 if (dict == NULL) {
3379 dict = PyDict_New();
3380 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003381 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003382 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003383 }
3384
Guido van Rossum687ae002001-10-15 22:03:32 +00003385 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003386 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003387 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003388 if (type->tp_methods != NULL) {
3389 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003390 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003391 }
3392 if (type->tp_members != NULL) {
3393 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003394 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003395 }
3396 if (type->tp_getset != NULL) {
3397 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003398 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003399 }
3400
Tim Peters6d6c1a32001-08-02 04:15:00 +00003401 /* Calculate method resolution order */
3402 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003403 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003404 }
3405
Guido van Rossum13d52f02001-08-10 21:24:08 +00003406 /* Inherit special flags from dominant base */
3407 if (type->tp_base != NULL)
3408 inherit_special(type, type->tp_base);
3409
Tim Peters6d6c1a32001-08-02 04:15:00 +00003410 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003411 bases = type->tp_mro;
3412 assert(bases != NULL);
3413 assert(PyTuple_Check(bases));
3414 n = PyTuple_GET_SIZE(bases);
3415 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003416 PyObject *b = PyTuple_GET_ITEM(bases, i);
3417 if (PyType_Check(b))
3418 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003419 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003420
Tim Peters3cfe7542003-05-21 21:29:48 +00003421 /* Sanity check for tp_free. */
3422 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3423 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003424 /* This base class needs to call tp_free, but doesn't have
3425 * one, or its tp_free is for non-gc'ed objects.
3426 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003427 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3428 "gc and is a base type but has inappropriate "
3429 "tp_free slot",
3430 type->tp_name);
3431 goto error;
3432 }
3433
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003434 /* if the type dictionary doesn't contain a __doc__, set it from
3435 the tp_doc slot.
3436 */
3437 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3438 if (type->tp_doc != NULL) {
3439 PyObject *doc = PyString_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003440 if (doc == NULL)
3441 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003442 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3443 Py_DECREF(doc);
3444 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003445 PyDict_SetItemString(type->tp_dict,
3446 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003447 }
3448 }
3449
Guido van Rossum38938152006-08-21 23:36:26 +00003450 /* Hack for tp_hash and __hash__.
3451 If after all that, tp_hash is still NULL, and __hash__ is not in
3452 tp_dict, set tp_dict['__hash__'] equal to None.
3453 This signals that __hash__ is not inherited.
3454 */
3455 if (type->tp_hash == NULL) {
3456 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3457 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3458 goto error;
3459 }
3460 }
3461
Guido van Rossum13d52f02001-08-10 21:24:08 +00003462 /* Some more special stuff */
3463 base = type->tp_base;
3464 if (base != NULL) {
3465 if (type->tp_as_number == NULL)
3466 type->tp_as_number = base->tp_as_number;
3467 if (type->tp_as_sequence == NULL)
3468 type->tp_as_sequence = base->tp_as_sequence;
3469 if (type->tp_as_mapping == NULL)
3470 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003471 if (type->tp_as_buffer == NULL)
3472 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003473 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003474
Guido van Rossum1c450732001-10-08 15:18:27 +00003475 /* Link into each base class's list of subclasses */
3476 bases = type->tp_bases;
3477 n = PyTuple_GET_SIZE(bases);
3478 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003479 PyObject *b = PyTuple_GET_ITEM(bases, i);
3480 if (PyType_Check(b) &&
3481 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003482 goto error;
3483 }
3484
Guido van Rossum13d52f02001-08-10 21:24:08 +00003485 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003486 assert(type->tp_dict != NULL);
3487 type->tp_flags =
3488 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003490
3491 error:
3492 type->tp_flags &= ~Py_TPFLAGS_READYING;
3493 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003494}
3495
Guido van Rossum1c450732001-10-08 15:18:27 +00003496static int
3497add_subclass(PyTypeObject *base, PyTypeObject *type)
3498{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003499 Py_ssize_t i;
3500 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003501 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003502
3503 list = base->tp_subclasses;
3504 if (list == NULL) {
3505 base->tp_subclasses = list = PyList_New(0);
3506 if (list == NULL)
3507 return -1;
3508 }
3509 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003510 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003511 i = PyList_GET_SIZE(list);
3512 while (--i >= 0) {
3513 ref = PyList_GET_ITEM(list, i);
3514 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003515 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003516 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003517 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003518 result = PyList_Append(list, newobj);
3519 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003520 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003521}
3522
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003523static void
3524remove_subclass(PyTypeObject *base, PyTypeObject *type)
3525{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003526 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003527 PyObject *list, *ref;
3528
3529 list = base->tp_subclasses;
3530 if (list == NULL) {
3531 return;
3532 }
3533 assert(PyList_Check(list));
3534 i = PyList_GET_SIZE(list);
3535 while (--i >= 0) {
3536 ref = PyList_GET_ITEM(list, i);
3537 assert(PyWeakref_CheckRef(ref));
3538 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3539 /* this can't fail, right? */
3540 PySequence_DelItem(list, i);
3541 return;
3542 }
3543 }
3544}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003545
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003546static int
3547check_num_args(PyObject *ob, int n)
3548{
3549 if (!PyTuple_CheckExact(ob)) {
3550 PyErr_SetString(PyExc_SystemError,
3551 "PyArg_UnpackTuple() argument list is not a tuple");
3552 return 0;
3553 }
3554 if (n == PyTuple_GET_SIZE(ob))
3555 return 1;
3556 PyErr_Format(
3557 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003558 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003559 return 0;
3560}
3561
Tim Peters6d6c1a32001-08-02 04:15:00 +00003562/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3563
3564/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003565 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003566 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3567 Most tables have only one entry; the tables for binary operators have two
3568 entries, one regular and one with reversed arguments. */
3569
3570static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003571wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003572{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003573 lenfunc func = (lenfunc)wrapped;
3574 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003575
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003576 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003577 return NULL;
3578 res = (*func)(self);
3579 if (res == -1 && PyErr_Occurred())
3580 return NULL;
3581 return PyInt_FromLong((long)res);
3582}
3583
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003585wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3586{
3587 inquiry func = (inquiry)wrapped;
3588 int res;
3589
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003590 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003591 return NULL;
3592 res = (*func)(self);
3593 if (res == -1 && PyErr_Occurred())
3594 return NULL;
3595 return PyBool_FromLong((long)res);
3596}
3597
3598static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003599wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3600{
3601 binaryfunc func = (binaryfunc)wrapped;
3602 PyObject *other;
3603
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003604 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003605 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003606 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003607 return (*func)(self, other);
3608}
3609
3610static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003611wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3612{
3613 binaryfunc func = (binaryfunc)wrapped;
3614 PyObject *other;
3615
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003616 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003617 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003618 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003619 return (*func)(self, other);
3620}
3621
3622static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003623wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3624{
3625 binaryfunc func = (binaryfunc)wrapped;
3626 PyObject *other;
3627
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003628 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003630 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003631 if (!PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003632 Py_INCREF(Py_NotImplemented);
3633 return Py_NotImplemented;
3634 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003635 return (*func)(other, self);
3636}
3637
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003638static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3640{
3641 ternaryfunc func = (ternaryfunc)wrapped;
3642 PyObject *other;
3643 PyObject *third = Py_None;
3644
3645 /* Note: This wrapper only works for __pow__() */
3646
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003647 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003648 return NULL;
3649 return (*func)(self, other, third);
3650}
3651
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003652static PyObject *
3653wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3654{
3655 ternaryfunc func = (ternaryfunc)wrapped;
3656 PyObject *other;
3657 PyObject *third = Py_None;
3658
3659 /* Note: This wrapper only works for __pow__() */
3660
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003661 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003662 return NULL;
3663 return (*func)(other, self, third);
3664}
3665
Tim Peters6d6c1a32001-08-02 04:15:00 +00003666static PyObject *
3667wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3668{
3669 unaryfunc func = (unaryfunc)wrapped;
3670
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003671 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003672 return NULL;
3673 return (*func)(self);
3674}
3675
Tim Peters6d6c1a32001-08-02 04:15:00 +00003676static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003677wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003678{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003679 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003680 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003681 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003682
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003683 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3684 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003685 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003686 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003687 return NULL;
3688 return (*func)(self, i);
3689}
3690
Martin v. Löwis18e16552006-02-15 17:27:45 +00003691static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003692getindex(PyObject *self, PyObject *arg)
3693{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003694 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003695
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003696 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003697 if (i == -1 && PyErr_Occurred())
3698 return -1;
3699 if (i < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003700 PySequenceMethods *sq = Py_Type(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003701 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003702 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003703 if (n < 0)
3704 return -1;
3705 i += n;
3706 }
3707 }
3708 return i;
3709}
3710
3711static PyObject *
3712wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3713{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003714 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003715 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003716 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003717
Guido van Rossumf4593e02001-10-03 12:09:30 +00003718 if (PyTuple_GET_SIZE(args) == 1) {
3719 arg = PyTuple_GET_ITEM(args, 0);
3720 i = getindex(self, arg);
3721 if (i == -1 && PyErr_Occurred())
3722 return NULL;
3723 return (*func)(self, i);
3724 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003725 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003726 assert(PyErr_Occurred());
3727 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003728}
3729
Tim Peters6d6c1a32001-08-02 04:15:00 +00003730static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003731wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003732{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003733 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3734 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003735
Martin v. Löwis18e16552006-02-15 17:27:45 +00003736 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003737 return NULL;
3738 return (*func)(self, i, j);
3739}
3740
Tim Peters6d6c1a32001-08-02 04:15:00 +00003741static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003742wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003743{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003744 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3745 Py_ssize_t i;
3746 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003747 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003748
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003749 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003750 return NULL;
3751 i = getindex(self, arg);
3752 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003753 return NULL;
3754 res = (*func)(self, i, value);
3755 if (res == -1 && PyErr_Occurred())
3756 return NULL;
3757 Py_INCREF(Py_None);
3758 return Py_None;
3759}
3760
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003761static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003762wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003763{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003764 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3765 Py_ssize_t i;
3766 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003767 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003768
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003769 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003770 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003771 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003772 i = getindex(self, arg);
3773 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003774 return NULL;
3775 res = (*func)(self, i, NULL);
3776 if (res == -1 && PyErr_Occurred())
3777 return NULL;
3778 Py_INCREF(Py_None);
3779 return Py_None;
3780}
3781
Tim Peters6d6c1a32001-08-02 04:15:00 +00003782static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003783wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003784{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003785 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3786 Py_ssize_t i, j;
3787 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003788 PyObject *value;
3789
Martin v. Löwis18e16552006-02-15 17:27:45 +00003790 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791 return NULL;
3792 res = (*func)(self, i, j, value);
3793 if (res == -1 && PyErr_Occurred())
3794 return NULL;
3795 Py_INCREF(Py_None);
3796 return Py_None;
3797}
3798
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003799static PyObject *
3800wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3801{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003802 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3803 Py_ssize_t i, j;
3804 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003805
Martin v. Löwis18e16552006-02-15 17:27:45 +00003806 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003807 return NULL;
3808 res = (*func)(self, i, j, NULL);
3809 if (res == -1 && PyErr_Occurred())
3810 return NULL;
3811 Py_INCREF(Py_None);
3812 return Py_None;
3813}
3814
Tim Peters6d6c1a32001-08-02 04:15:00 +00003815/* XXX objobjproc is a misnomer; should be objargpred */
3816static PyObject *
3817wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3818{
3819 objobjproc func = (objobjproc)wrapped;
3820 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003821 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003823 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003824 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003825 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003826 res = (*func)(self, value);
3827 if (res == -1 && PyErr_Occurred())
3828 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003829 else
3830 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003831}
3832
Tim Peters6d6c1a32001-08-02 04:15:00 +00003833static PyObject *
3834wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3835{
3836 objobjargproc func = (objobjargproc)wrapped;
3837 int res;
3838 PyObject *key, *value;
3839
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003840 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003841 return NULL;
3842 res = (*func)(self, key, value);
3843 if (res == -1 && PyErr_Occurred())
3844 return NULL;
3845 Py_INCREF(Py_None);
3846 return Py_None;
3847}
3848
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003849static PyObject *
3850wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3851{
3852 objobjargproc func = (objobjargproc)wrapped;
3853 int res;
3854 PyObject *key;
3855
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003856 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003857 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003858 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003859 res = (*func)(self, key, NULL);
3860 if (res == -1 && PyErr_Occurred())
3861 return NULL;
3862 Py_INCREF(Py_None);
3863 return Py_None;
3864}
3865
Tim Peters6d6c1a32001-08-02 04:15:00 +00003866static PyObject *
3867wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3868{
3869 cmpfunc func = (cmpfunc)wrapped;
3870 int res;
3871 PyObject *other;
3872
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003873 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003875 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003876 if (Py_Type(other)->tp_compare != func &&
3877 !PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003878 PyErr_Format(
3879 PyExc_TypeError,
3880 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003881 Py_Type(self)->tp_name,
3882 Py_Type(self)->tp_name,
3883 Py_Type(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00003884 return NULL;
3885 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886 res = (*func)(self, other);
3887 if (PyErr_Occurred())
3888 return NULL;
3889 return PyInt_FromLong((long)res);
3890}
3891
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003892/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003893 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003894static int
3895hackcheck(PyObject *self, setattrofunc func, char *what)
3896{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003897 PyTypeObject *type = Py_Type(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003898 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3899 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003900 /* If type is NULL now, this is a really weird type.
3901 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003902 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003903 PyErr_Format(PyExc_TypeError,
3904 "can't apply this %s to %s object",
3905 what,
3906 type->tp_name);
3907 return 0;
3908 }
3909 return 1;
3910}
3911
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912static PyObject *
3913wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3914{
3915 setattrofunc func = (setattrofunc)wrapped;
3916 int res;
3917 PyObject *name, *value;
3918
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003919 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003920 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003921 if (!hackcheck(self, func, "__setattr__"))
3922 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003923 res = (*func)(self, name, value);
3924 if (res < 0)
3925 return NULL;
3926 Py_INCREF(Py_None);
3927 return Py_None;
3928}
3929
3930static PyObject *
3931wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3932{
3933 setattrofunc func = (setattrofunc)wrapped;
3934 int res;
3935 PyObject *name;
3936
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003937 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003938 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003939 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003940 if (!hackcheck(self, func, "__delattr__"))
3941 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003942 res = (*func)(self, name, NULL);
3943 if (res < 0)
3944 return NULL;
3945 Py_INCREF(Py_None);
3946 return Py_None;
3947}
3948
Tim Peters6d6c1a32001-08-02 04:15:00 +00003949static PyObject *
3950wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3951{
3952 hashfunc func = (hashfunc)wrapped;
3953 long res;
3954
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003955 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003956 return NULL;
3957 res = (*func)(self);
3958 if (res == -1 && PyErr_Occurred())
3959 return NULL;
3960 return PyInt_FromLong(res);
3961}
3962
Tim Peters6d6c1a32001-08-02 04:15:00 +00003963static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00003964wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965{
3966 ternaryfunc func = (ternaryfunc)wrapped;
3967
Guido van Rossumc8e56452001-10-22 00:43:43 +00003968 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003969}
3970
Tim Peters6d6c1a32001-08-02 04:15:00 +00003971static PyObject *
3972wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3973{
3974 richcmpfunc func = (richcmpfunc)wrapped;
3975 PyObject *other;
3976
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003977 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003979 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003980 return (*func)(self, other, op);
3981}
3982
3983#undef RICHCMP_WRAPPER
3984#define RICHCMP_WRAPPER(NAME, OP) \
3985static PyObject * \
3986richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3987{ \
3988 return wrap_richcmpfunc(self, args, wrapped, OP); \
3989}
3990
Jack Jansen8e938b42001-08-08 15:29:49 +00003991RICHCMP_WRAPPER(lt, Py_LT)
3992RICHCMP_WRAPPER(le, Py_LE)
3993RICHCMP_WRAPPER(eq, Py_EQ)
3994RICHCMP_WRAPPER(ne, Py_NE)
3995RICHCMP_WRAPPER(gt, Py_GT)
3996RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003997
Tim Peters6d6c1a32001-08-02 04:15:00 +00003998static PyObject *
3999wrap_next(PyObject *self, PyObject *args, void *wrapped)
4000{
4001 unaryfunc func = (unaryfunc)wrapped;
4002 PyObject *res;
4003
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004004 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004005 return NULL;
4006 res = (*func)(self);
4007 if (res == NULL && !PyErr_Occurred())
4008 PyErr_SetNone(PyExc_StopIteration);
4009 return res;
4010}
4011
Tim Peters6d6c1a32001-08-02 04:15:00 +00004012static PyObject *
4013wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4014{
4015 descrgetfunc func = (descrgetfunc)wrapped;
4016 PyObject *obj;
4017 PyObject *type = NULL;
4018
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004019 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004020 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004021 if (obj == Py_None)
4022 obj = NULL;
4023 if (type == Py_None)
4024 type = NULL;
4025 if (type == NULL &&obj == NULL) {
4026 PyErr_SetString(PyExc_TypeError,
4027 "__get__(None, None) is invalid");
4028 return NULL;
4029 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004030 return (*func)(self, obj, type);
4031}
4032
Tim Peters6d6c1a32001-08-02 04:15:00 +00004033static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004034wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035{
4036 descrsetfunc func = (descrsetfunc)wrapped;
4037 PyObject *obj, *value;
4038 int ret;
4039
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004040 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004041 return NULL;
4042 ret = (*func)(self, obj, value);
4043 if (ret < 0)
4044 return NULL;
4045 Py_INCREF(Py_None);
4046 return Py_None;
4047}
Guido van Rossum22b13872002-08-06 21:41:44 +00004048
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004049static PyObject *
4050wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4051{
4052 descrsetfunc func = (descrsetfunc)wrapped;
4053 PyObject *obj;
4054 int ret;
4055
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004056 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004057 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004058 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004059 ret = (*func)(self, obj, NULL);
4060 if (ret < 0)
4061 return NULL;
4062 Py_INCREF(Py_None);
4063 return Py_None;
4064}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004065
Tim Peters6d6c1a32001-08-02 04:15:00 +00004066static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004067wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068{
4069 initproc func = (initproc)wrapped;
4070
Guido van Rossumc8e56452001-10-22 00:43:43 +00004071 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072 return NULL;
4073 Py_INCREF(Py_None);
4074 return Py_None;
4075}
4076
Tim Peters6d6c1a32001-08-02 04:15:00 +00004077static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004078tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079{
Barry Warsaw60f01882001-08-22 19:24:42 +00004080 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004081 PyObject *arg0, *res;
4082
4083 if (self == NULL || !PyType_Check(self))
4084 Py_FatalError("__new__() called with non-type 'self'");
4085 type = (PyTypeObject *)self;
4086 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004087 PyErr_Format(PyExc_TypeError,
4088 "%s.__new__(): not enough arguments",
4089 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004090 return NULL;
4091 }
4092 arg0 = PyTuple_GET_ITEM(args, 0);
4093 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004094 PyErr_Format(PyExc_TypeError,
4095 "%s.__new__(X): X is not a type object (%s)",
4096 type->tp_name,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004097 Py_Type(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004098 return NULL;
4099 }
4100 subtype = (PyTypeObject *)arg0;
4101 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004102 PyErr_Format(PyExc_TypeError,
4103 "%s.__new__(%s): %s is not a subtype of %s",
4104 type->tp_name,
4105 subtype->tp_name,
4106 subtype->tp_name,
4107 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004108 return NULL;
4109 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004110
4111 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004112 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004113 most derived base that's not a heap type is this type. */
4114 staticbase = subtype;
4115 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4116 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004117 /* If staticbase is NULL now, it is a really weird type.
4118 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004119 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004120 PyErr_Format(PyExc_TypeError,
4121 "%s.__new__(%s) is not safe, use %s.__new__()",
4122 type->tp_name,
4123 subtype->tp_name,
4124 staticbase == NULL ? "?" : staticbase->tp_name);
4125 return NULL;
4126 }
4127
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004128 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4129 if (args == NULL)
4130 return NULL;
4131 res = type->tp_new(subtype, args, kwds);
4132 Py_DECREF(args);
4133 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004134}
4135
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004136static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004137 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004138 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004139 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004140 {0}
4141};
4142
4143static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004144add_tp_new_wrapper(PyTypeObject *type)
4145{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004146 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004147
Guido van Rossum687ae002001-10-15 22:03:32 +00004148 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004149 return 0;
4150 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004151 if (func == NULL)
4152 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004153 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004154 Py_DECREF(func);
4155 return -1;
4156 }
4157 Py_DECREF(func);
4158 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004159}
4160
Guido van Rossumf040ede2001-08-07 16:40:56 +00004161/* Slot wrappers that call the corresponding __foo__ slot. See comments
4162 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004163
Guido van Rossumdc91b992001-08-08 22:26:22 +00004164#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004165static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004166FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004167{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004168 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004169 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004170}
4171
Guido van Rossumdc91b992001-08-08 22:26:22 +00004172#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004173static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004174FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004175{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004176 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004177 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178}
4179
Guido van Rossumcd118802003-01-06 22:57:47 +00004180/* Boolean helper for SLOT1BINFULL().
4181 right.__class__ is a nontrivial subclass of left.__class__. */
4182static int
4183method_is_overloaded(PyObject *left, PyObject *right, char *name)
4184{
4185 PyObject *a, *b;
4186 int ok;
4187
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004188 b = PyObject_GetAttrString((PyObject *)(Py_Type(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004189 if (b == NULL) {
4190 PyErr_Clear();
4191 /* If right doesn't have it, it's not overloaded */
4192 return 0;
4193 }
4194
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004195 a = PyObject_GetAttrString((PyObject *)(Py_Type(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004196 if (a == NULL) {
4197 PyErr_Clear();
4198 Py_DECREF(b);
4199 /* If right has it but left doesn't, it's overloaded */
4200 return 1;
4201 }
4202
4203 ok = PyObject_RichCompareBool(a, b, Py_NE);
4204 Py_DECREF(a);
4205 Py_DECREF(b);
4206 if (ok < 0) {
4207 PyErr_Clear();
4208 return 0;
4209 }
4210
4211 return ok;
4212}
4213
Guido van Rossumdc91b992001-08-08 22:26:22 +00004214
4215#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004216static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004217FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004218{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004219 static PyObject *cache_str, *rcache_str; \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004220 int do_other = Py_Type(self) != Py_Type(other) && \
4221 Py_Type(other)->tp_as_number != NULL && \
4222 Py_Type(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4223 if (Py_Type(self)->tp_as_number != NULL && \
4224 Py_Type(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004225 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004226 if (do_other && \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004227 PyType_IsSubtype(Py_Type(other), Py_Type(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004228 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004229 r = call_maybe( \
4230 other, ROPSTR, &rcache_str, "(O)", self); \
4231 if (r != Py_NotImplemented) \
4232 return r; \
4233 Py_DECREF(r); \
4234 do_other = 0; \
4235 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004236 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004237 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004238 if (r != Py_NotImplemented || \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004239 Py_Type(other) == Py_Type(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004240 return r; \
4241 Py_DECREF(r); \
4242 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004243 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004244 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004245 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004246 } \
4247 Py_INCREF(Py_NotImplemented); \
4248 return Py_NotImplemented; \
4249}
4250
4251#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4252 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4253
4254#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4255static PyObject * \
4256FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4257{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004258 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004259 return call_method(self, OPSTR, &cache_str, \
4260 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004261}
4262
Martin v. Löwis18e16552006-02-15 17:27:45 +00004263static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264slot_sq_length(PyObject *self)
4265{
Guido van Rossum2730b132001-08-28 18:22:14 +00004266 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004267 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004268 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004269
4270 if (res == NULL)
4271 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004272 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004273 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004274 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004275 if (!PyErr_Occurred())
4276 PyErr_SetString(PyExc_ValueError,
4277 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004278 return -1;
4279 }
Guido van Rossum26111622001-10-01 16:42:49 +00004280 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004281}
4282
Guido van Rossumf4593e02001-10-03 12:09:30 +00004283/* Super-optimized version of slot_sq_item.
4284 Other slots could do the same... */
4285static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004286slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004287{
4288 static PyObject *getitem_str;
4289 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4290 descrgetfunc f;
4291
4292 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004293 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004294 if (getitem_str == NULL)
4295 return NULL;
4296 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004297 func = _PyType_Lookup(Py_Type(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004298 if (func != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004299 if ((f = Py_Type(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004300 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004301 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004302 func = f(func, self, (PyObject *)(Py_Type(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004303 if (func == NULL) {
4304 return NULL;
4305 }
4306 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004307 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004308 if (ival != NULL) {
4309 args = PyTuple_New(1);
4310 if (args != NULL) {
4311 PyTuple_SET_ITEM(args, 0, ival);
4312 retval = PyObject_Call(func, args, NULL);
4313 Py_XDECREF(args);
4314 Py_XDECREF(func);
4315 return retval;
4316 }
4317 }
4318 }
4319 else {
4320 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4321 }
4322 Py_XDECREF(args);
4323 Py_XDECREF(ival);
4324 Py_XDECREF(func);
4325 return NULL;
4326}
4327
Martin v. Löwis18e16552006-02-15 17:27:45 +00004328SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004329
4330static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004331slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332{
4333 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004334 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004335
4336 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004337 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004338 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004339 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004340 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004341 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342 if (res == NULL)
4343 return -1;
4344 Py_DECREF(res);
4345 return 0;
4346}
4347
4348static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004349slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004350{
4351 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004352 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004353
4354 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004355 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004356 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004357 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004358 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004359 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004360 if (res == NULL)
4361 return -1;
4362 Py_DECREF(res);
4363 return 0;
4364}
4365
4366static int
4367slot_sq_contains(PyObject *self, PyObject *value)
4368{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004369 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004370 int result = -1;
4371
Guido van Rossum60718732001-08-28 17:47:51 +00004372 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373
Guido van Rossum55f20992001-10-01 17:18:22 +00004374 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004375 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004376 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004377 if (args == NULL)
4378 res = NULL;
4379 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004380 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004381 Py_DECREF(args);
4382 }
4383 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004384 if (res != NULL) {
4385 result = PyObject_IsTrue(res);
4386 Py_DECREF(res);
4387 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004388 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004389 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004390 /* Possible results: -1 and 1 */
4391 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004392 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004393 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004394 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004395}
4396
Tim Peters6d6c1a32001-08-02 04:15:00 +00004397#define slot_mp_length slot_sq_length
4398
Guido van Rossumdc91b992001-08-08 22:26:22 +00004399SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004400
4401static int
4402slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4403{
4404 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004405 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004406
4407 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004408 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004409 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004410 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004411 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004412 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004413 if (res == NULL)
4414 return -1;
4415 Py_DECREF(res);
4416 return 0;
4417}
4418
Guido van Rossumdc91b992001-08-08 22:26:22 +00004419SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4420SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4421SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004422SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4423SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4424
Jeremy Hylton938ace62002-07-17 16:30:39 +00004425static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004426
4427SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4428 nb_power, "__pow__", "__rpow__")
4429
4430static PyObject *
4431slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4432{
Guido van Rossum2730b132001-08-28 18:22:14 +00004433 static PyObject *pow_str;
4434
Guido van Rossumdc91b992001-08-08 22:26:22 +00004435 if (modulus == Py_None)
4436 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004437 /* Three-arg power doesn't use __rpow__. But ternary_op
4438 can call this when the second argument's type uses
4439 slot_nb_power, so check before calling self.__pow__. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004440 if (Py_Type(self)->tp_as_number != NULL &&
4441 Py_Type(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004442 return call_method(self, "__pow__", &pow_str,
4443 "(OO)", other, modulus);
4444 }
4445 Py_INCREF(Py_NotImplemented);
4446 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004447}
4448
4449SLOT0(slot_nb_negative, "__neg__")
4450SLOT0(slot_nb_positive, "__pos__")
4451SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004452
4453static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004454slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004455{
Tim Petersea7f75d2002-12-07 21:39:16 +00004456 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004457 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004458 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004459 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004460
Jack Diederich4dafcc42006-11-28 19:15:13 +00004461 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004462 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004463 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004464 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004465 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004466 if (func == NULL)
4467 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004468 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004469 }
4470 args = PyTuple_New(0);
4471 if (args != NULL) {
4472 PyObject *temp = PyObject_Call(func, args, NULL);
4473 Py_DECREF(args);
4474 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004475 if (from_len) {
4476 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004477 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004478 }
4479 else if (PyBool_Check(temp)) {
4480 result = PyObject_IsTrue(temp);
4481 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004482 else {
4483 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004484 "__bool__ should return "
4485 "bool, returned %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004486 Py_Type(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004487 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004488 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004489 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004490 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004491 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004492 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004493 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004494}
4495
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004496
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004497static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004498slot_nb_index(PyObject *self)
4499{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004500 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004501 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004502}
4503
4504
Guido van Rossumdc91b992001-08-08 22:26:22 +00004505SLOT0(slot_nb_invert, "__invert__")
4506SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4507SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4508SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4509SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4510SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004511
Guido van Rossumdc91b992001-08-08 22:26:22 +00004512SLOT0(slot_nb_int, "__int__")
4513SLOT0(slot_nb_long, "__long__")
4514SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004515SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4516SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4517SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004518SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004519/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4520static PyObject *
4521slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4522{
4523 static PyObject *cache_str;
4524 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4525}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004526SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4527SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4528SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4529SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4530SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4531SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4532 "__floordiv__", "__rfloordiv__")
4533SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4534SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4535SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004536
4537static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004538half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004539{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004540 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004541 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004542 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004543
Guido van Rossum60718732001-08-28 17:47:51 +00004544 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004545 if (func == NULL) {
4546 PyErr_Clear();
4547 }
4548 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004549 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004550 if (args == NULL)
4551 res = NULL;
4552 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004553 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004554 Py_DECREF(args);
4555 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004556 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004557 if (res != Py_NotImplemented) {
4558 if (res == NULL)
4559 return -2;
4560 c = PyInt_AsLong(res);
4561 Py_DECREF(res);
4562 if (c == -1 && PyErr_Occurred())
4563 return -2;
4564 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4565 }
4566 Py_DECREF(res);
4567 }
4568 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004569}
4570
Guido van Rossumab3b0342001-09-18 20:38:53 +00004571/* This slot is published for the benefit of try_3way_compare in object.c */
4572int
4573_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004574{
4575 int c;
4576
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004577 if (Py_Type(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004578 c = half_compare(self, other);
4579 if (c <= 1)
4580 return c;
4581 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004582 if (Py_Type(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004583 c = half_compare(other, self);
4584 if (c < -1)
4585 return -2;
4586 if (c <= 1)
4587 return -c;
4588 }
4589 return (void *)self < (void *)other ? -1 :
4590 (void *)self > (void *)other ? 1 : 0;
4591}
4592
4593static PyObject *
4594slot_tp_repr(PyObject *self)
4595{
4596 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004597 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004598
Guido van Rossum60718732001-08-28 17:47:51 +00004599 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004600 if (func != NULL) {
4601 res = PyEval_CallObject(func, NULL);
4602 Py_DECREF(func);
4603 return res;
4604 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004605 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004606 return PyUnicode_FromFormat("<%s object at %p>",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004607 Py_Type(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004608}
4609
4610static PyObject *
4611slot_tp_str(PyObject *self)
4612{
4613 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004614 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004615
Guido van Rossum60718732001-08-28 17:47:51 +00004616 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004617 if (func != NULL) {
4618 res = PyEval_CallObject(func, NULL);
4619 Py_DECREF(func);
4620 return res;
4621 }
4622 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004623 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004624 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004625 res = slot_tp_repr(self);
4626 if (!res)
4627 return NULL;
4628 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4629 Py_DECREF(res);
4630 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004631 }
4632}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004633
4634static long
4635slot_tp_hash(PyObject *self)
4636{
Guido van Rossum4011a242006-08-17 23:09:57 +00004637 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004638 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004639 long h;
4640
Guido van Rossum60718732001-08-28 17:47:51 +00004641 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004642
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004643 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004644 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004645 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004646 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004647
4648 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004649 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004650 Py_Type(self)->tp_name);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004651 return -1;
4652 }
4653
Guido van Rossum4011a242006-08-17 23:09:57 +00004654 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004655 Py_DECREF(func);
4656 if (res == NULL)
4657 return -1;
4658 if (PyLong_Check(res))
4659 h = PyLong_Type.tp_hash(res);
4660 else
4661 h = PyInt_AsLong(res);
4662 Py_DECREF(res);
4663 if (h == -1 && !PyErr_Occurred())
4664 h = -2;
4665 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004666}
4667
4668static PyObject *
4669slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4670{
Guido van Rossum60718732001-08-28 17:47:51 +00004671 static PyObject *call_str;
4672 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004673 PyObject *res;
4674
4675 if (meth == NULL)
4676 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004677
4678 /* PyObject_Call() will end up calling slot_tp_call() again if
4679 the object returned for __call__ has __call__ itself defined
4680 upon it. This can be an infinite recursion if you set
4681 __call__ in a class to an instance of it. */
4682 if (Py_EnterRecursiveCall(" in __call__")) {
4683 Py_DECREF(meth);
4684 return NULL;
4685 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004686 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004687 Py_LeaveRecursiveCall();
4688
Tim Peters6d6c1a32001-08-02 04:15:00 +00004689 Py_DECREF(meth);
4690 return res;
4691}
4692
Guido van Rossum14a6f832001-10-17 13:59:09 +00004693/* There are two slot dispatch functions for tp_getattro.
4694
4695 - slot_tp_getattro() is used when __getattribute__ is overridden
4696 but no __getattr__ hook is present;
4697
4698 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4699
Guido van Rossumc334df52002-04-04 23:44:47 +00004700 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4701 detects the absence of __getattr__ and then installs the simpler slot if
4702 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004703
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704static PyObject *
4705slot_tp_getattro(PyObject *self, PyObject *name)
4706{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004707 static PyObject *getattribute_str = NULL;
4708 return call_method(self, "__getattribute__", &getattribute_str,
4709 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004710}
4711
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004712static PyObject *
4713slot_tp_getattr_hook(PyObject *self, PyObject *name)
4714{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004715 PyTypeObject *tp = Py_Type(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004716 PyObject *getattr, *getattribute, *res;
4717 static PyObject *getattribute_str = NULL;
4718 static PyObject *getattr_str = NULL;
4719
4720 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004721 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004722 if (getattr_str == NULL)
4723 return NULL;
4724 }
4725 if (getattribute_str == NULL) {
4726 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004727 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004728 if (getattribute_str == NULL)
4729 return NULL;
4730 }
4731 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004732 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004733 /* No __getattr__ hook: use a simpler dispatcher */
4734 tp->tp_getattro = slot_tp_getattro;
4735 return slot_tp_getattro(self, name);
4736 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004737 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004738 if (getattribute == NULL ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004739 (Py_Type(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00004740 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4741 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004742 res = PyObject_GenericGetAttr(self, name);
4743 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004744 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004745 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004746 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004747 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004748 }
4749 return res;
4750}
4751
Tim Peters6d6c1a32001-08-02 04:15:00 +00004752static int
4753slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4754{
4755 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004756 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004757
4758 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004759 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004760 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004761 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004762 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004763 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004764 if (res == NULL)
4765 return -1;
4766 Py_DECREF(res);
4767 return 0;
4768}
4769
Tim Peters6d6c1a32001-08-02 04:15:00 +00004770static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004771half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004772{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004773 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004774 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004775
Guido van Rossum60718732001-08-28 17:47:51 +00004776 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004777 if (func == NULL) {
4778 PyErr_Clear();
4779 Py_INCREF(Py_NotImplemented);
4780 return Py_NotImplemented;
4781 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004782 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004783 if (args == NULL)
4784 res = NULL;
4785 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004786 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004787 Py_DECREF(args);
4788 }
4789 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790 return res;
4791}
4792
Guido van Rossumb8f63662001-08-15 23:57:02 +00004793static PyObject *
4794slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4795{
4796 PyObject *res;
4797
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004798 if (Py_Type(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004799 res = half_richcompare(self, other, op);
4800 if (res != Py_NotImplemented)
4801 return res;
4802 Py_DECREF(res);
4803 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004804 if (Py_Type(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004805 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004806 if (res != Py_NotImplemented) {
4807 return res;
4808 }
4809 Py_DECREF(res);
4810 }
4811 Py_INCREF(Py_NotImplemented);
4812 return Py_NotImplemented;
4813}
4814
4815static PyObject *
4816slot_tp_iter(PyObject *self)
4817{
4818 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004819 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004820
Guido van Rossum60718732001-08-28 17:47:51 +00004821 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004822 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004823 PyObject *args;
4824 args = res = PyTuple_New(0);
4825 if (args != NULL) {
4826 res = PyObject_Call(func, args, NULL);
4827 Py_DECREF(args);
4828 }
4829 Py_DECREF(func);
4830 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004831 }
4832 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004833 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004834 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004835 PyErr_Format(PyExc_TypeError,
4836 "'%.200s' object is not iterable",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004837 Py_Type(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004838 return NULL;
4839 }
4840 Py_DECREF(func);
4841 return PySeqIter_New(self);
4842}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004843
4844static PyObject *
4845slot_tp_iternext(PyObject *self)
4846{
Guido van Rossum2730b132001-08-28 18:22:14 +00004847 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00004848 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004849}
4850
Guido van Rossum1a493502001-08-17 16:47:50 +00004851static PyObject *
4852slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4853{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004854 PyTypeObject *tp = Py_Type(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00004855 PyObject *get;
4856 static PyObject *get_str = NULL;
4857
4858 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004859 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00004860 if (get_str == NULL)
4861 return NULL;
4862 }
4863 get = _PyType_Lookup(tp, get_str);
4864 if (get == NULL) {
4865 /* Avoid further slowdowns */
4866 if (tp->tp_descr_get == slot_tp_descr_get)
4867 tp->tp_descr_get = NULL;
4868 Py_INCREF(self);
4869 return self;
4870 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004871 if (obj == NULL)
4872 obj = Py_None;
4873 if (type == NULL)
4874 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004875 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004876}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004877
4878static int
4879slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4880{
Guido van Rossum2c252392001-08-24 10:13:31 +00004881 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004882 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004883
4884 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004885 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004886 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004887 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004888 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004889 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004890 if (res == NULL)
4891 return -1;
4892 Py_DECREF(res);
4893 return 0;
4894}
4895
4896static int
4897slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4898{
Guido van Rossum60718732001-08-28 17:47:51 +00004899 static PyObject *init_str;
4900 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004901 PyObject *res;
4902
4903 if (meth == NULL)
4904 return -1;
4905 res = PyObject_Call(meth, args, kwds);
4906 Py_DECREF(meth);
4907 if (res == NULL)
4908 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004909 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004910 PyErr_Format(PyExc_TypeError,
4911 "__init__() should return None, not '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004912 Py_Type(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004913 Py_DECREF(res);
4914 return -1;
4915 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004916 Py_DECREF(res);
4917 return 0;
4918}
4919
4920static PyObject *
4921slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4922{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004923 static PyObject *new_str;
4924 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004925 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004926 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004927
Guido van Rossum7bed2132002-08-08 21:57:53 +00004928 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004929 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00004930 if (new_str == NULL)
4931 return NULL;
4932 }
4933 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004934 if (func == NULL)
4935 return NULL;
4936 assert(PyTuple_Check(args));
4937 n = PyTuple_GET_SIZE(args);
4938 newargs = PyTuple_New(n+1);
4939 if (newargs == NULL)
4940 return NULL;
4941 Py_INCREF(type);
4942 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4943 for (i = 0; i < n; i++) {
4944 x = PyTuple_GET_ITEM(args, i);
4945 Py_INCREF(x);
4946 PyTuple_SET_ITEM(newargs, i+1, x);
4947 }
4948 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004949 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004950 Py_DECREF(func);
4951 return x;
4952}
4953
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004954static void
4955slot_tp_del(PyObject *self)
4956{
4957 static PyObject *del_str = NULL;
4958 PyObject *del, *res;
4959 PyObject *error_type, *error_value, *error_traceback;
4960
4961 /* Temporarily resurrect the object. */
4962 assert(self->ob_refcnt == 0);
4963 self->ob_refcnt = 1;
4964
4965 /* Save the current exception, if any. */
4966 PyErr_Fetch(&error_type, &error_value, &error_traceback);
4967
4968 /* Execute __del__ method, if any. */
4969 del = lookup_maybe(self, "__del__", &del_str);
4970 if (del != NULL) {
4971 res = PyEval_CallObject(del, NULL);
4972 if (res == NULL)
4973 PyErr_WriteUnraisable(del);
4974 else
4975 Py_DECREF(res);
4976 Py_DECREF(del);
4977 }
4978
4979 /* Restore the saved exception. */
4980 PyErr_Restore(error_type, error_value, error_traceback);
4981
4982 /* Undo the temporary resurrection; can't use DECREF here, it would
4983 * cause a recursive call.
4984 */
4985 assert(self->ob_refcnt > 0);
4986 if (--self->ob_refcnt == 0)
4987 return; /* this is the normal path out */
4988
4989 /* __del__ resurrected it! Make it look like the original Py_DECREF
4990 * never happened.
4991 */
4992 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004993 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004994 _Py_NewReference(self);
4995 self->ob_refcnt = refcnt;
4996 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004997 assert(!PyType_IS_GC(Py_Type(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004998 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00004999 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5000 * we need to undo that. */
5001 _Py_DEC_REFTOTAL;
5002 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5003 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005004 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5005 * _Py_NewReference bumped tp_allocs: both of those need to be
5006 * undone.
5007 */
5008#ifdef COUNT_ALLOCS
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005009 --Py_Type(self)->tp_frees;
5010 --Py_Type(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005011#endif
5012}
5013
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005014
5015/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005016 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005017 structure, which incorporates the additional structures used for numbers,
5018 sequences and mappings.
5019 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005020 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005021 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5022 terminated with an all-zero entry. (This table is further initialized and
5023 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005024
Guido van Rossum6d204072001-10-21 00:44:31 +00005025typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005026
5027#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005028#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005029#undef ETSLOT
5030#undef SQSLOT
5031#undef MPSLOT
5032#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005033#undef UNSLOT
5034#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005035#undef BINSLOT
5036#undef RBINSLOT
5037
Guido van Rossum6d204072001-10-21 00:44:31 +00005038#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005039 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5040 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005041#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5042 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005043 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005044#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005045 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005046 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005047#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5048 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5049#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5050 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5051#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5052 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5053#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5054 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5055 "x." NAME "() <==> " DOC)
5056#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5057 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5058 "x." NAME "(y) <==> x" DOC "y")
5059#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5060 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5061 "x." NAME "(y) <==> x" DOC "y")
5062#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5063 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5064 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005065#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5066 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5067 "x." NAME "(y) <==> " DOC)
5068#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5069 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5070 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005071
5072static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005073 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005074 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005075 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5076 The logic in abstract.c always falls back to nb_add/nb_multiply in
5077 this case. Defining both the nb_* and the sq_* slots to call the
5078 user-defined methods has unexpected side-effects, as shown by
5079 test_descr.notimplemented() */
5080 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005081 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005082 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005083 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005084 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005085 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005086 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5087 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005088 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005089 "x.__getslice__(i, j) <==> x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005090 \n\
5091 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005092 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005093 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005094 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005095 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005096 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005097 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005098 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005099 \n\
5100 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005101 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005102 "x.__delslice__(i, j) <==> del x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005103 \n\
5104 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005105 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5106 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005107 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005108 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005109 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005110 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005111
Martin v. Löwis18e16552006-02-15 17:27:45 +00005112 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005113 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005114 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005115 wrap_binaryfunc,
5116 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005117 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005118 wrap_objobjargproc,
5119 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005120 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005121 wrap_delitem,
5122 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005123
Guido van Rossum6d204072001-10-21 00:44:31 +00005124 BINSLOT("__add__", nb_add, slot_nb_add,
5125 "+"),
5126 RBINSLOT("__radd__", nb_add, slot_nb_add,
5127 "+"),
5128 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5129 "-"),
5130 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5131 "-"),
5132 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5133 "*"),
5134 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5135 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005136 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5137 "%"),
5138 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5139 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005140 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005141 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005142 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005143 "divmod(y, x)"),
5144 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5145 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5146 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5147 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5148 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5149 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5150 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5151 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005152 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005153 "x != 0"),
5154 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5155 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5156 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5157 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5158 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5159 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5160 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5161 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5162 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5163 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5164 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005165 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5166 "int(x)"),
5167 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5168 "long(x)"),
5169 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5170 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005171 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005172 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005173 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5174 wrap_binaryfunc, "+"),
5175 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5176 wrap_binaryfunc, "-"),
5177 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5178 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005179 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5180 wrap_binaryfunc, "%"),
5181 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005182 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005183 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5184 wrap_binaryfunc, "<<"),
5185 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5186 wrap_binaryfunc, ">>"),
5187 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5188 wrap_binaryfunc, "&"),
5189 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5190 wrap_binaryfunc, "^"),
5191 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5192 wrap_binaryfunc, "|"),
5193 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5194 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5195 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5196 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5197 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5198 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5199 IBSLOT("__itruediv__", nb_inplace_true_divide,
5200 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005201
Guido van Rossum6d204072001-10-21 00:44:31 +00005202 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5203 "x.__str__() <==> str(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005204 TPSLOT("__str__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005205 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5206 "x.__repr__() <==> repr(x)"),
Guido van Rossumafe7a942001-10-29 14:33:44 +00005207 TPSLOT("__repr__", tp_print, NULL, NULL, ""),
Guido van Rossum6d204072001-10-21 00:44:31 +00005208 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5209 "x.__cmp__(y) <==> cmp(x,y)"),
5210 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5211 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005212 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5213 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005214 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005215 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5216 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5217 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5218 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5219 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5220 "x.__setattr__('name', value) <==> x.name = value"),
5221 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5222 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5223 "x.__delattr__('name') <==> del x.name"),
5224 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5225 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5226 "x.__lt__(y) <==> x<y"),
5227 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5228 "x.__le__(y) <==> x<=y"),
5229 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5230 "x.__eq__(y) <==> x==y"),
5231 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5232 "x.__ne__(y) <==> x!=y"),
5233 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5234 "x.__gt__(y) <==> x>y"),
5235 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5236 "x.__ge__(y) <==> x>=y"),
5237 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5238 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005239 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5240 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005241 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5242 "descr.__get__(obj[, type]) -> value"),
5243 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5244 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005245 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5246 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005247 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005248 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005249 "see x.__class__.__doc__ for signature",
5250 PyWrapperFlag_KEYWORDS),
5251 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005252 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005253 {NULL}
5254};
5255
Guido van Rossumc334df52002-04-04 23:44:47 +00005256/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005257 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005258 the offset to the type pointer, since it takes care to indirect through the
5259 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5260 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005261static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005262slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005263{
5264 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005265 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005266
Guido van Rossume5c691a2003-03-07 15:13:17 +00005267 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005268 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005269 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5270 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5271 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005272 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005273 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005274 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5275 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005276 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005277 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005278 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5279 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005280 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005281 }
5282 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005283 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005284 }
5285 if (ptr != NULL)
5286 ptr += offset;
5287 return (void **)ptr;
5288}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005289
Guido van Rossumc334df52002-04-04 23:44:47 +00005290/* Length of array of slotdef pointers used to store slots with the
5291 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5292 the same __name__, for any __name__. Since that's a static property, it is
5293 appropriate to declare fixed-size arrays for this. */
5294#define MAX_EQUIV 10
5295
5296/* Return a slot pointer for a given name, but ONLY if the attribute has
5297 exactly one slot function. The name must be an interned string. */
5298static void **
5299resolve_slotdups(PyTypeObject *type, PyObject *name)
5300{
5301 /* XXX Maybe this could be optimized more -- but is it worth it? */
5302
5303 /* pname and ptrs act as a little cache */
5304 static PyObject *pname;
5305 static slotdef *ptrs[MAX_EQUIV];
5306 slotdef *p, **pp;
5307 void **res, **ptr;
5308
5309 if (pname != name) {
5310 /* Collect all slotdefs that match name into ptrs. */
5311 pname = name;
5312 pp = ptrs;
5313 for (p = slotdefs; p->name_strobj; p++) {
5314 if (p->name_strobj == name)
5315 *pp++ = p;
5316 }
5317 *pp = NULL;
5318 }
5319
5320 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005321 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005322 res = NULL;
5323 for (pp = ptrs; *pp; pp++) {
5324 ptr = slotptr(type, (*pp)->offset);
5325 if (ptr == NULL || *ptr == NULL)
5326 continue;
5327 if (res != NULL)
5328 return NULL;
5329 res = ptr;
5330 }
5331 return res;
5332}
5333
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005334/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005335 does some incredibly complex thinking and then sticks something into the
5336 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5337 interests, and then stores a generic wrapper or a specific function into
5338 the slot.) Return a pointer to the next slotdef with a different offset,
5339 because that's convenient for fixup_slot_dispatchers(). */
5340static slotdef *
5341update_one_slot(PyTypeObject *type, slotdef *p)
5342{
5343 PyObject *descr;
5344 PyWrapperDescrObject *d;
5345 void *generic = NULL, *specific = NULL;
5346 int use_generic = 0;
5347 int offset = p->offset;
5348 void **ptr = slotptr(type, offset);
5349
5350 if (ptr == NULL) {
5351 do {
5352 ++p;
5353 } while (p->offset == offset);
5354 return p;
5355 }
5356 do {
5357 descr = _PyType_Lookup(type, p->name_strobj);
5358 if (descr == NULL)
5359 continue;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005360 if (Py_Type(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005361 void **tptr = resolve_slotdups(type, p->name_strobj);
5362 if (tptr == NULL || tptr == ptr)
5363 generic = p->function;
5364 d = (PyWrapperDescrObject *)descr;
5365 if (d->d_base->wrapper == p->wrapper &&
5366 PyType_IsSubtype(type, d->d_type))
5367 {
5368 if (specific == NULL ||
5369 specific == d->d_wrapped)
5370 specific = d->d_wrapped;
5371 else
5372 use_generic = 1;
5373 }
5374 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005375 else if (Py_Type(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005376 PyCFunction_GET_FUNCTION(descr) ==
5377 (PyCFunction)tp_new_wrapper &&
5378 strcmp(p->name, "__new__") == 0)
5379 {
5380 /* The __new__ wrapper is not a wrapper descriptor,
5381 so must be special-cased differently.
5382 If we don't do this, creating an instance will
5383 always use slot_tp_new which will look up
5384 __new__ in the MRO which will call tp_new_wrapper
5385 which will look through the base classes looking
5386 for a static base and call its tp_new (usually
5387 PyType_GenericNew), after performing various
5388 sanity checks and constructing a new argument
5389 list. Cut all that nonsense short -- this speeds
5390 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005391 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005392 /* XXX I'm not 100% sure that there isn't a hole
5393 in this reasoning that requires additional
5394 sanity checks. I'll buy the first person to
5395 point out a bug in this reasoning a beer. */
5396 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005397 else {
5398 use_generic = 1;
5399 generic = p->function;
5400 }
5401 } while ((++p)->offset == offset);
5402 if (specific && !use_generic)
5403 *ptr = specific;
5404 else
5405 *ptr = generic;
5406 return p;
5407}
5408
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005409/* In the type, update the slots whose slotdefs are gathered in the pp array.
5410 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005411static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005412update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005413{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005414 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005415
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005416 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005417 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005418 return 0;
5419}
5420
Guido van Rossumc334df52002-04-04 23:44:47 +00005421/* Comparison function for qsort() to compare slotdefs by their offset, and
5422 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005423static int
5424slotdef_cmp(const void *aa, const void *bb)
5425{
5426 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5427 int c = a->offset - b->offset;
5428 if (c != 0)
5429 return c;
5430 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005431 /* Cannot use a-b, as this gives off_t,
5432 which may lose precision when converted to int. */
5433 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005434}
5435
Guido van Rossumc334df52002-04-04 23:44:47 +00005436/* Initialize the slotdefs table by adding interned string objects for the
5437 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005438static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005439init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005440{
5441 slotdef *p;
5442 static int initialized = 0;
5443
5444 if (initialized)
5445 return;
5446 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005447 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005448 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005449 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005450 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005451 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5452 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005453 initialized = 1;
5454}
5455
Guido van Rossumc334df52002-04-04 23:44:47 +00005456/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005457static int
5458update_slot(PyTypeObject *type, PyObject *name)
5459{
Guido van Rossumc334df52002-04-04 23:44:47 +00005460 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005461 slotdef *p;
5462 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005463 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005464
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005465 init_slotdefs();
5466 pp = ptrs;
5467 for (p = slotdefs; p->name; p++) {
5468 /* XXX assume name is interned! */
5469 if (p->name_strobj == name)
5470 *pp++ = p;
5471 }
5472 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005473 for (pp = ptrs; *pp; pp++) {
5474 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005475 offset = p->offset;
5476 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005477 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005478 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005479 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005480 if (ptrs[0] == NULL)
5481 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005482 return update_subclasses(type, name,
5483 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005484}
5485
Guido van Rossumc334df52002-04-04 23:44:47 +00005486/* Store the proper functions in the slot dispatches at class (type)
5487 definition time, based upon which operations the class overrides in its
5488 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005489static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005490fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005491{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005492 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005493
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005494 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005495 for (p = slotdefs; p->name; )
5496 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005497}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005498
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005499static void
5500update_all_slots(PyTypeObject* type)
5501{
5502 slotdef *p;
5503
5504 init_slotdefs();
5505 for (p = slotdefs; p->name; p++) {
5506 /* update_slot returns int but can't actually fail */
5507 update_slot(type, p->name_strobj);
5508 }
5509}
5510
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005511/* recurse_down_subclasses() and update_subclasses() are mutually
5512 recursive functions to call a callback for all subclasses,
5513 but refraining from recursing into subclasses that define 'name'. */
5514
5515static int
5516update_subclasses(PyTypeObject *type, PyObject *name,
5517 update_callback callback, void *data)
5518{
5519 if (callback(type, data) < 0)
5520 return -1;
5521 return recurse_down_subclasses(type, name, callback, data);
5522}
5523
5524static int
5525recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5526 update_callback callback, void *data)
5527{
5528 PyTypeObject *subclass;
5529 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005530 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005531
5532 subclasses = type->tp_subclasses;
5533 if (subclasses == NULL)
5534 return 0;
5535 assert(PyList_Check(subclasses));
5536 n = PyList_GET_SIZE(subclasses);
5537 for (i = 0; i < n; i++) {
5538 ref = PyList_GET_ITEM(subclasses, i);
5539 assert(PyWeakref_CheckRef(ref));
5540 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5541 assert(subclass != NULL);
5542 if ((PyObject *)subclass == Py_None)
5543 continue;
5544 assert(PyType_Check(subclass));
5545 /* Avoid recursing down into unaffected classes */
5546 dict = subclass->tp_dict;
5547 if (dict != NULL && PyDict_Check(dict) &&
5548 PyDict_GetItem(dict, name) != NULL)
5549 continue;
5550 if (update_subclasses(subclass, name, callback, data) < 0)
5551 return -1;
5552 }
5553 return 0;
5554}
5555
Guido van Rossum6d204072001-10-21 00:44:31 +00005556/* This function is called by PyType_Ready() to populate the type's
5557 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005558 function slot (like tp_repr) that's defined in the type, one or more
5559 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005560 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005561 cause more than one descriptor to be added (for example, the nb_add
5562 slot adds both __add__ and __radd__ descriptors) and some function
5563 slots compete for the same descriptor (for example both sq_item and
5564 mp_subscript generate a __getitem__ descriptor).
5565
Guido van Rossumd8faa362007-04-27 19:54:29 +00005566 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005567 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005568 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005569 between competing slots: the members of PyHeapTypeObject are listed
5570 from most general to least general, so the most general slot is
5571 preferred. In particular, because as_mapping comes before as_sequence,
5572 for a type that defines both mp_subscript and sq_item, mp_subscript
5573 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005574
5575 This only adds new descriptors and doesn't overwrite entries in
5576 tp_dict that were previously defined. The descriptors contain a
5577 reference to the C function they must call, so that it's safe if they
5578 are copied into a subtype's __dict__ and the subtype has a different
5579 C function in its slot -- calling the method defined by the
5580 descriptor will call the C function that was used to create it,
5581 rather than the C function present in the slot when it is called.
5582 (This is important because a subtype may have a C function in the
5583 slot that calls the method from the dictionary, and we want to avoid
5584 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005585
5586static int
5587add_operators(PyTypeObject *type)
5588{
5589 PyObject *dict = type->tp_dict;
5590 slotdef *p;
5591 PyObject *descr;
5592 void **ptr;
5593
5594 init_slotdefs();
5595 for (p = slotdefs; p->name; p++) {
5596 if (p->wrapper == NULL)
5597 continue;
5598 ptr = slotptr(type, p->offset);
5599 if (!ptr || !*ptr)
5600 continue;
5601 if (PyDict_GetItem(dict, p->name_strobj))
5602 continue;
5603 descr = PyDescr_NewWrapper(type, p, *ptr);
5604 if (descr == NULL)
5605 return -1;
5606 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5607 return -1;
5608 Py_DECREF(descr);
5609 }
5610 if (type->tp_new != NULL) {
5611 if (add_tp_new_wrapper(type) < 0)
5612 return -1;
5613 }
5614 return 0;
5615}
5616
Guido van Rossum705f0f52001-08-24 16:47:00 +00005617
5618/* Cooperative 'super' */
5619
5620typedef struct {
5621 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005622 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005623 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005624 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005625} superobject;
5626
Guido van Rossum6f799372001-09-20 20:46:19 +00005627static PyMemberDef super_members[] = {
5628 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5629 "the class invoking super()"},
5630 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5631 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005632 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005633 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005634 {0}
5635};
5636
Guido van Rossum705f0f52001-08-24 16:47:00 +00005637static void
5638super_dealloc(PyObject *self)
5639{
5640 superobject *su = (superobject *)self;
5641
Guido van Rossum048eb752001-10-02 21:24:57 +00005642 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005643 Py_XDECREF(su->obj);
5644 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005645 Py_XDECREF(su->obj_type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005646 Py_Type(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005647}
5648
5649static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005650super_repr(PyObject *self)
5651{
5652 superobject *su = (superobject *)self;
5653
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005654 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005655 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005656 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005657 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005658 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005659 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005660 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005661 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005662 su->type ? su->type->tp_name : "NULL");
5663}
5664
5665static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005666super_getattro(PyObject *self, PyObject *name)
5667{
5668 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005669 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005670
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005671 if (!skip) {
5672 /* We want __class__ to return the class of the super object
5673 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005674 skip = (PyUnicode_Check(name) &&
5675 PyUnicode_GET_SIZE(name) == 9 &&
5676 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005677 }
5678
5679 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005680 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005681 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005682 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005683 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005684
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005685 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005686 mro = starttype->tp_mro;
5687
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005688 if (mro == NULL)
5689 n = 0;
5690 else {
5691 assert(PyTuple_Check(mro));
5692 n = PyTuple_GET_SIZE(mro);
5693 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005694 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005695 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005696 break;
5697 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005698 i++;
5699 res = NULL;
5700 for (; i < n; i++) {
5701 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005702 if (PyType_Check(tmp))
5703 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005704 else
5705 continue;
5706 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005707 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005708 Py_INCREF(res);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005709 f = Py_Type(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005710 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005711 tmp = f(res,
5712 /* Only pass 'obj' param if
5713 this is instance-mode super
5714 (See SF ID #743627)
5715 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005716 (su->obj == (PyObject *)
5717 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005718 ? (PyObject *)NULL
5719 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005720 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005721 Py_DECREF(res);
5722 res = tmp;
5723 }
5724 return res;
5725 }
5726 }
5727 }
5728 return PyObject_GenericGetAttr(self, name);
5729}
5730
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005731static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005732supercheck(PyTypeObject *type, PyObject *obj)
5733{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005734 /* Check that a super() call makes sense. Return a type object.
5735
5736 obj can be a new-style class, or an instance of one:
5737
Guido van Rossumd8faa362007-04-27 19:54:29 +00005738 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005739 used for class methods; the return value is obj.
5740
5741 - If it is an instance, it must be an instance of 'type'. This is
5742 the normal case; the return value is obj.__class__.
5743
5744 But... when obj is an instance, we want to allow for the case where
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005745 Py_Type(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005746 This will allow using super() with a proxy for obj.
5747 */
5748
Guido van Rossum8e80a722003-02-18 19:22:22 +00005749 /* Check for first bullet above (special case) */
5750 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5751 Py_INCREF(obj);
5752 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005753 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005754
5755 /* Normal case */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005756 if (PyType_IsSubtype(Py_Type(obj), type)) {
5757 Py_INCREF(Py_Type(obj));
5758 return Py_Type(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005759 }
5760 else {
5761 /* Try the slow way */
5762 static PyObject *class_str = NULL;
5763 PyObject *class_attr;
5764
5765 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005766 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005767 if (class_str == NULL)
5768 return NULL;
5769 }
5770
5771 class_attr = PyObject_GetAttr(obj, class_str);
5772
5773 if (class_attr != NULL &&
5774 PyType_Check(class_attr) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005775 (PyTypeObject *)class_attr != Py_Type(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005776 {
5777 int ok = PyType_IsSubtype(
5778 (PyTypeObject *)class_attr, type);
5779 if (ok)
5780 return (PyTypeObject *)class_attr;
5781 }
5782
5783 if (class_attr == NULL)
5784 PyErr_Clear();
5785 else
5786 Py_DECREF(class_attr);
5787 }
5788
Guido van Rossumd8faa362007-04-27 19:54:29 +00005789 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005790 "super(type, obj): "
5791 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005792 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005793}
5794
Guido van Rossum705f0f52001-08-24 16:47:00 +00005795static PyObject *
5796super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5797{
5798 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005799 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005800
5801 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5802 /* Not binding to an object, or already bound */
5803 Py_INCREF(self);
5804 return self;
5805 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005806 if (Py_Type(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005807 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005808 call its type */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005809 return PyObject_CallFunctionObjArgs((PyObject *)Py_Type(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00005810 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005811 else {
5812 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005813 PyTypeObject *obj_type = supercheck(su->type, obj);
5814 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005815 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005816 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005817 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005818 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005819 return NULL;
5820 Py_INCREF(su->type);
5821 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005822 newobj->type = su->type;
5823 newobj->obj = obj;
5824 newobj->obj_type = obj_type;
5825 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005826 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005827}
5828
5829static int
5830super_init(PyObject *self, PyObject *args, PyObject *kwds)
5831{
5832 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005833 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00005834 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005835 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005836
Thomas Wouters89f507f2006-12-13 04:49:30 +00005837 if (!_PyArg_NoKeywords("super", kwds))
5838 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005839 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005840 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005841
5842 if (type == NULL) {
5843 /* Call super(), without args -- fill in from __class__
5844 and first local variable on the stack. */
5845 PyFrameObject *f = PyThreadState_GET()->frame;
5846 PyCodeObject *co = f->f_code;
5847 int i, n;
5848 if (co == NULL) {
5849 PyErr_SetString(PyExc_SystemError,
5850 "super(): no code object");
5851 return -1;
5852 }
5853 if (co->co_argcount == 0) {
5854 PyErr_SetString(PyExc_SystemError,
5855 "super(): no arguments");
5856 return -1;
5857 }
5858 obj = f->f_localsplus[0];
5859 if (obj == NULL) {
5860 PyErr_SetString(PyExc_SystemError,
5861 "super(): arg[0] deleted");
5862 return -1;
5863 }
5864 if (co->co_freevars == NULL)
5865 n = 0;
5866 else {
5867 assert(PyTuple_Check(co->co_freevars));
5868 n = PyTuple_GET_SIZE(co->co_freevars);
5869 }
5870 for (i = 0; i < n; i++) {
5871 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
5872 assert(PyUnicode_Check(name));
5873 if (!PyUnicode_CompareWithASCIIString(name,
5874 "__class__")) {
5875 PyObject *cell =
5876 f->f_localsplus[co->co_nlocals + i];
5877 if (cell == NULL || !PyCell_Check(cell)) {
5878 PyErr_SetString(PyExc_SystemError,
5879 "super(): bad __class__ cell");
5880 return -1;
5881 }
5882 type = (PyTypeObject *) PyCell_GET(cell);
5883 if (type == NULL) {
5884 PyErr_SetString(PyExc_SystemError,
5885 "super(): empty __class__ cell");
5886 return -1;
5887 }
5888 if (!PyType_Check(type)) {
5889 PyErr_Format(PyExc_SystemError,
5890 "super(): __class__ is not a type (%s)",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005891 Py_Type(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005892 return -1;
5893 }
5894 break;
5895 }
5896 }
5897 if (type == NULL) {
5898 PyErr_SetString(PyExc_SystemError,
5899 "super(): __class__ cell not found");
5900 return -1;
5901 }
5902 }
5903
Guido van Rossum705f0f52001-08-24 16:47:00 +00005904 if (obj == Py_None)
5905 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005906 if (obj != NULL) {
5907 obj_type = supercheck(type, obj);
5908 if (obj_type == NULL)
5909 return -1;
5910 Py_INCREF(obj);
5911 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005912 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005913 su->type = type;
5914 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005915 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005916 return 0;
5917}
5918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005919PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005920"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005921"super(type) -> unbound super object\n"
5922"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005923"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005924"Typical use to call a cooperative superclass method:\n"
5925"class C(B):\n"
5926" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005927" super().meth(arg)\n"
5928"This works for class methods too:\n"
5929"class C(B):\n"
5930" @classmethod\n"
5931" def cmeth(cls, arg):\n"
5932" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005933
Guido van Rossum048eb752001-10-02 21:24:57 +00005934static int
5935super_traverse(PyObject *self, visitproc visit, void *arg)
5936{
5937 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005938
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005939 Py_VISIT(su->obj);
5940 Py_VISIT(su->type);
5941 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005942
5943 return 0;
5944}
5945
Guido van Rossum705f0f52001-08-24 16:47:00 +00005946PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005947 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005948 "super", /* tp_name */
5949 sizeof(superobject), /* tp_basicsize */
5950 0, /* tp_itemsize */
5951 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005952 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005953 0, /* tp_print */
5954 0, /* tp_getattr */
5955 0, /* tp_setattr */
5956 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005957 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005958 0, /* tp_as_number */
5959 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005960 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005961 0, /* tp_hash */
5962 0, /* tp_call */
5963 0, /* tp_str */
5964 super_getattro, /* tp_getattro */
5965 0, /* tp_setattro */
5966 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00005967 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5968 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005969 super_doc, /* tp_doc */
5970 super_traverse, /* tp_traverse */
5971 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005972 0, /* tp_richcompare */
5973 0, /* tp_weaklistoffset */
5974 0, /* tp_iter */
5975 0, /* tp_iternext */
5976 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005977 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005978 0, /* tp_getset */
5979 0, /* tp_base */
5980 0, /* tp_dict */
5981 super_descr_get, /* tp_descr_get */
5982 0, /* tp_descr_set */
5983 0, /* tp_dictoffset */
5984 super_init, /* tp_init */
5985 PyType_GenericAlloc, /* tp_alloc */
5986 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005987 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005988};