blob: 0cc63fc2b5c04dd57a8af80dac8f3a6e316e13d9 [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;
Neal Norwitz80e7f272007-08-26 06:45:23 +000047 char *tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000048
49 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
50 PyErr_Format(PyExc_TypeError,
51 "can't set %s.__name__", type->tp_name);
52 return -1;
53 }
54 if (!value) {
55 PyErr_Format(PyExc_TypeError,
56 "can't delete %s.__name__", type->tp_name);
57 return -1;
58 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +000059 if (!PyUnicode_Check(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +000060 PyErr_Format(PyExc_TypeError,
61 "can only assign string to %s.__name__, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000062 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +000063 return -1;
64 }
Neal Norwitz80e7f272007-08-26 06:45:23 +000065 tp_name = PyUnicode_AsString(value);
66 if (tp_name == NULL)
Neal Norwitz6ea45d32007-08-26 04:19:43 +000067 return -1;
Neal Norwitz80e7f272007-08-26 06:45:23 +000068 if (strlen(tp_name) != (size_t)PyUnicode_GET_SIZE(value)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +000069 PyErr_Format(PyExc_ValueError,
70 "__name__ must not contain null bytes");
71 return -1;
72 }
73
Guido van Rossume5c691a2003-03-07 15:13:17 +000074 et = (PyHeapTypeObject*)type;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000075
76 Py_INCREF(value);
77
Georg Brandlc255c7b2006-02-20 22:27:28 +000078 Py_DECREF(et->ht_name);
79 et->ht_name = value;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000080
Neal Norwitz80e7f272007-08-26 06:45:23 +000081 type->tp_name = tp_name;
Michael W. Hudson98bbc492002-11-26 14:47:27 +000082
83 return 0;
84}
85
Guido van Rossumc3542212001-08-16 09:18:56 +000086static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +000087type_module(PyTypeObject *type, void *context)
Guido van Rossum29ca26e1995-01-07 11:58:15 +000088{
Guido van Rossumc3542212001-08-16 09:18:56 +000089 PyObject *mod;
90 char *s;
91
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000092 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
93 mod = PyDict_GetItemString(type->tp_dict, "__module__");
Anthony Baxter3ecdb252004-06-11 14:41:18 +000094 if (!mod) {
95 PyErr_Format(PyExc_AttributeError, "__module__");
96 return 0;
97 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +000098 Py_XINCREF(mod);
Guido van Rossumc3542212001-08-16 09:18:56 +000099 return mod;
100 }
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000101 else {
102 s = strrchr(type->tp_name, '.');
103 if (s != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000104 return PyUnicode_FromStringAndSize(
Thomas Wouters89f507f2006-12-13 04:49:30 +0000105 type->tp_name, (Py_ssize_t)(s - type->tp_name));
Martin v. Löwis5b222132007-06-10 09:51:05 +0000106 return PyUnicode_FromString("__builtin__");
Michael W. Hudsonade8c8b22002-11-27 16:29:26 +0000107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000108}
109
Guido van Rossum3926a632001-09-25 16:25:58 +0000110static int
111type_set_module(PyTypeObject *type, PyObject *value, void *context)
112{
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000113 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
Guido van Rossum3926a632001-09-25 16:25:58 +0000114 PyErr_Format(PyExc_TypeError,
115 "can't set %s.__module__", type->tp_name);
116 return -1;
117 }
118 if (!value) {
119 PyErr_Format(PyExc_TypeError,
120 "can't delete %s.__module__", type->tp_name);
121 return -1;
122 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000123
Guido van Rossum3926a632001-09-25 16:25:58 +0000124 return PyDict_SetItemString(type->tp_dict, "__module__", value);
125}
126
Tim Peters6d6c1a32001-08-02 04:15:00 +0000127static PyObject *
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000128type_get_bases(PyTypeObject *type, void *context)
129{
130 Py_INCREF(type->tp_bases);
131 return type->tp_bases;
132}
133
134static PyTypeObject *best_base(PyObject *);
135static int mro_internal(PyTypeObject *);
136static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
137static int add_subclass(PyTypeObject*, PyTypeObject*);
138static void remove_subclass(PyTypeObject *, PyTypeObject *);
139static void update_all_slots(PyTypeObject *);
140
Guido van Rossum8d24ee92003-03-24 23:49:49 +0000141typedef int (*update_callback)(PyTypeObject *, void *);
142static int update_subclasses(PyTypeObject *type, PyObject *name,
143 update_callback callback, void *data);
144static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
145 update_callback callback, void *data);
146
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000147static int
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000148mro_subclasses(PyTypeObject *type, PyObject* temp)
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000149{
150 PyTypeObject *subclass;
151 PyObject *ref, *subclasses, *old_mro;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000152 Py_ssize_t i, n;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000153
154 subclasses = type->tp_subclasses;
155 if (subclasses == NULL)
156 return 0;
157 assert(PyList_Check(subclasses));
158 n = PyList_GET_SIZE(subclasses);
159 for (i = 0; i < n; i++) {
160 ref = PyList_GET_ITEM(subclasses, i);
161 assert(PyWeakref_CheckRef(ref));
162 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
163 assert(subclass != NULL);
164 if ((PyObject *)subclass == Py_None)
165 continue;
166 assert(PyType_Check(subclass));
167 old_mro = subclass->tp_mro;
168 if (mro_internal(subclass) < 0) {
169 subclass->tp_mro = old_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000170 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000171 }
172 else {
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000173 PyObject* tuple;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000174 tuple = PyTuple_Pack(2, subclass, old_mro);
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000175 Py_DECREF(old_mro);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000176 if (!tuple)
177 return -1;
178 if (PyList_Append(temp, tuple) < 0)
179 return -1;
Guido van Rossum19a02ba2003-04-15 22:09:45 +0000180 Py_DECREF(tuple);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000181 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000182 if (mro_subclasses(subclass, temp) < 0)
183 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000184 }
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000185 return 0;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000186}
187
188static int
189type_set_bases(PyTypeObject *type, PyObject *value, void *context)
190{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000191 Py_ssize_t i;
192 int r = 0;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000193 PyObject *ob, *temp;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000194 PyTypeObject *new_base, *old_base;
195 PyObject *old_bases, *old_mro;
196
197 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
198 PyErr_Format(PyExc_TypeError,
199 "can't set %s.__bases__", type->tp_name);
200 return -1;
201 }
202 if (!value) {
203 PyErr_Format(PyExc_TypeError,
204 "can't delete %s.__bases__", type->tp_name);
205 return -1;
206 }
207 if (!PyTuple_Check(value)) {
208 PyErr_Format(PyExc_TypeError,
209 "can only assign tuple to %s.__bases__, not %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000210 type->tp_name, Py_Type(value)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000211 return -1;
212 }
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +0000213 if (PyTuple_GET_SIZE(value) == 0) {
214 PyErr_Format(PyExc_TypeError,
215 "can only assign non-empty tuple to %s.__bases__, not ()",
216 type->tp_name);
217 return -1;
218 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000219 for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
220 ob = PyTuple_GET_ITEM(value, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000221 if (!PyType_Check(ob)) {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000222 PyErr_Format(
223 PyExc_TypeError,
224 "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000225 type->tp_name, Py_Type(ob)->tp_name);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000226 return -1;
227 }
Michael W. Hudsoncaf17be2002-11-27 10:24:44 +0000228 if (PyType_Check(ob)) {
229 if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
230 PyErr_SetString(PyExc_TypeError,
231 "a __bases__ item causes an inheritance cycle");
232 return -1;
233 }
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000234 }
235 }
236
237 new_base = best_base(value);
238
239 if (!new_base) {
240 return -1;
241 }
242
243 if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
244 return -1;
245
246 Py_INCREF(new_base);
247 Py_INCREF(value);
248
249 old_bases = type->tp_bases;
250 old_base = type->tp_base;
251 old_mro = type->tp_mro;
252
253 type->tp_bases = value;
254 type->tp_base = new_base;
255
256 if (mro_internal(type) < 0) {
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000257 goto bail;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000258 }
259
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000260 temp = PyList_New(0);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000261 if (!temp)
262 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000263
264 r = mro_subclasses(type, temp);
265
266 if (r < 0) {
267 for (i = 0; i < PyList_Size(temp); i++) {
268 PyTypeObject* cls;
269 PyObject* mro;
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000270 PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
271 "", 2, 2, &cls, &mro);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272 Py_INCREF(mro);
273 ob = cls->tp_mro;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000274 cls->tp_mro = mro;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 Py_DECREF(ob);
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000276 }
277 Py_DECREF(temp);
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000278 goto bail;
Michael W. Hudson586da8f2002-11-27 15:20:19 +0000279 }
280
281 Py_DECREF(temp);
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000282
283 /* any base that was in __bases__ but now isn't, we
Raymond Hettingera8285862002-12-14 17:17:56 +0000284 need to remove |type| from its tp_subclasses.
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000285 conversely, any class now in __bases__ that wasn't
Raymond Hettingera8285862002-12-14 17:17:56 +0000286 needs to have |type| added to its subclasses. */
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000287
288 /* for now, sod that: just remove from all old_bases,
289 add to all new_bases */
290
291 for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
292 ob = PyTuple_GET_ITEM(old_bases, i);
293 if (PyType_Check(ob)) {
294 remove_subclass(
295 (PyTypeObject*)ob, type);
296 }
297 }
298
299 for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
300 ob = PyTuple_GET_ITEM(value, i);
301 if (PyType_Check(ob)) {
302 if (add_subclass((PyTypeObject*)ob, type) < 0)
303 r = -1;
304 }
305 }
306
307 update_all_slots(type);
308
309 Py_DECREF(old_bases);
310 Py_DECREF(old_base);
311 Py_DECREF(old_mro);
312
313 return r;
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000314
315 bail:
Michael W. Hudsone723e452003-08-07 14:58:10 +0000316 Py_DECREF(type->tp_bases);
317 Py_DECREF(type->tp_base);
318 if (type->tp_mro != old_mro) {
319 Py_DECREF(type->tp_mro);
320 }
321
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000322 type->tp_bases = old_bases;
323 type->tp_base = old_base;
324 type->tp_mro = old_mro;
Tim Petersea7f75d2002-12-07 21:39:16 +0000325
Michael W. Hudson7e7c00d2002-11-27 15:40:09 +0000326 return -1;
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000327}
328
329static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000330type_dict(PyTypeObject *type, void *context)
331{
332 if (type->tp_dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333 Py_INCREF(Py_None);
334 return Py_None;
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000335 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000336 return PyDictProxy_New(type->tp_dict);
Guido van Rossum29ca26e1995-01-07 11:58:15 +0000337}
338
Tim Peters24008312002-03-17 18:56:20 +0000339static PyObject *
340type_get_doc(PyTypeObject *type, void *context)
341{
342 PyObject *result;
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000343 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
Neal Norwitza369c5a2007-08-25 07:41:59 +0000344 return PyUnicode_FromString(type->tp_doc);
Tim Peters24008312002-03-17 18:56:20 +0000345 result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000346 if (result == NULL) {
347 result = Py_None;
348 Py_INCREF(result);
349 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000350 else if (Py_Type(result)->tp_descr_get) {
351 result = Py_Type(result)->tp_descr_get(result, NULL,
Tim Peters2b858972002-04-18 04:12:28 +0000352 (PyObject *)type);
Guido van Rossum6ca7d412002-04-18 00:22:00 +0000353 }
354 else {
355 Py_INCREF(result);
356 }
Tim Peters24008312002-03-17 18:56:20 +0000357 return result;
358}
359
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000360static PyGetSetDef type_getsets[] = {
Michael W. Hudson98bbc492002-11-26 14:47:27 +0000361 {"__name__", (getter)type_name, (setter)type_set_name, NULL},
362 {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
Guido van Rossum3926a632001-09-25 16:25:58 +0000363 {"__module__", (getter)type_module, (setter)type_set_module, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000364 {"__dict__", (getter)type_dict, NULL, NULL},
Tim Peters24008312002-03-17 18:56:20 +0000365 {"__doc__", (getter)type_get_doc, NULL, NULL},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000366 {0}
367};
368
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000370type_repr(PyTypeObject *type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371{
Barry Warsaw7ce36942001-08-24 18:34:26 +0000372 PyObject *mod, *name, *rtn;
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000373 char *kind;
Guido van Rossumc3542212001-08-16 09:18:56 +0000374
375 mod = type_module(type, NULL);
376 if (mod == NULL)
377 PyErr_Clear();
Martin v. Löwis5b222132007-06-10 09:51:05 +0000378 else if (!PyUnicode_Check(mod)) {
Guido van Rossumc3542212001-08-16 09:18:56 +0000379 Py_DECREF(mod);
380 mod = NULL;
381 }
382 name = type_name(type, NULL);
383 if (name == NULL)
384 return NULL;
Barry Warsaw7ce36942001-08-24 18:34:26 +0000385
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000386 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
387 kind = "class";
388 else
389 kind = "type";
390
Walter Dörwald75163602007-06-11 15:47:13 +0000391 if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "__builtin__"))
392 rtn = PyUnicode_FromFormat("<%s '%U.%U'>", kind, mod, name);
Guido van Rossumc3542212001-08-16 09:18:56 +0000393 else
Walter Dörwald1ab83302007-05-18 17:15:44 +0000394 rtn = PyUnicode_FromFormat("<%s '%s'>", kind, type->tp_name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000395
Guido van Rossumc3542212001-08-16 09:18:56 +0000396 Py_XDECREF(mod);
397 Py_DECREF(name);
Barry Warsaw7ce36942001-08-24 18:34:26 +0000398 return rtn;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Tim Peters6d6c1a32001-08-02 04:15:00 +0000401static PyObject *
402type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
403{
404 PyObject *obj;
405
406 if (type->tp_new == NULL) {
407 PyErr_Format(PyExc_TypeError,
408 "cannot create '%.100s' instances",
409 type->tp_name);
410 return NULL;
411 }
412
Tim Peters3f996e72001-09-13 19:18:27 +0000413 obj = type->tp_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000414 if (obj != NULL) {
Guido van Rossumf76de622001-10-18 15:49:21 +0000415 /* Ugly exception: when the call was type(something),
416 don't call tp_init on the result. */
417 if (type == &PyType_Type &&
418 PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
419 (kwds == NULL ||
420 (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
421 return obj;
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000422 /* If the returned object is not an instance of type,
423 it won't be initialized. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000424 if (!PyType_IsSubtype(Py_Type(obj), type))
Guido van Rossum8ace1ab2002-04-06 01:05:01 +0000425 return obj;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000426 type = Py_Type(obj);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000427 if (type->tp_init != NULL &&
Tim Peters6d6c1a32001-08-02 04:15:00 +0000428 type->tp_init(obj, args, kwds) < 0) {
429 Py_DECREF(obj);
430 obj = NULL;
431 }
432 }
433 return obj;
434}
435
436PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000438{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000439 PyObject *obj;
Guido van Rossume5c691a2003-03-07 15:13:17 +0000440 const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
441 /* note that we need to add one, for the sentinel */
Tim Peters406fe3b2001-10-06 19:04:01 +0000442
443 if (PyType_IS_GC(type))
Neil Schemenauer09a2ae52002-04-12 03:06:53 +0000444 obj = _PyObject_GC_Malloc(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000445 else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446 obj = (PyObject *)PyObject_MALLOC(size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000447
Neil Schemenauerc806c882001-08-29 23:54:54 +0000448 if (obj == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000449 return PyErr_NoMemory();
Tim Peters406fe3b2001-10-06 19:04:01 +0000450
Neil Schemenauerc806c882001-08-29 23:54:54 +0000451 memset(obj, '\0', size);
Tim Peters406fe3b2001-10-06 19:04:01 +0000452
Tim Peters6d6c1a32001-08-02 04:15:00 +0000453 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
454 Py_INCREF(type);
Tim Peters406fe3b2001-10-06 19:04:01 +0000455
Tim Peters6d6c1a32001-08-02 04:15:00 +0000456 if (type->tp_itemsize == 0)
457 PyObject_INIT(obj, type);
458 else
459 (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
Tim Peters406fe3b2001-10-06 19:04:01 +0000460
Tim Peters6d6c1a32001-08-02 04:15:00 +0000461 if (PyType_IS_GC(type))
Neil Schemenauerc806c882001-08-29 23:54:54 +0000462 _PyObject_GC_TRACK(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000463 return obj;
464}
465
466PyObject *
467PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
468{
469 return type->tp_alloc(type, 0);
470}
471
Guido van Rossum9475a232001-10-05 20:51:39 +0000472/* Helpers for subtyping */
473
474static int
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000475traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
476{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000478 PyMemberDef *mp;
479
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000480 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000481 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000482 for (i = 0; i < n; i++, mp++) {
483 if (mp->type == T_OBJECT_EX) {
484 char *addr = (char *)self + mp->offset;
485 PyObject *obj = *(PyObject **)addr;
486 if (obj != NULL) {
487 int err = visit(obj, arg);
488 if (err)
489 return err;
490 }
491 }
492 }
493 return 0;
494}
495
496static int
Guido van Rossum9475a232001-10-05 20:51:39 +0000497subtype_traverse(PyObject *self, visitproc visit, void *arg)
498{
499 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000500 traverseproc basetraverse;
Guido van Rossum9475a232001-10-05 20:51:39 +0000501
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000502 /* Find the nearest base with a different tp_traverse,
503 and traverse slots while we're at it */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000504 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000505 base = type;
506 while ((basetraverse = base->tp_traverse) == subtype_traverse) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000507 if (Py_Size(base)) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000508 int err = traverse_slots(base, self, visit, arg);
509 if (err)
510 return err;
511 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000512 base = base->tp_base;
513 assert(base);
514 }
515
516 if (type->tp_dictoffset != base->tp_dictoffset) {
517 PyObject **dictptr = _PyObject_GetDictPtr(self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000518 if (dictptr && *dictptr)
519 Py_VISIT(*dictptr);
Guido van Rossum9475a232001-10-05 20:51:39 +0000520 }
521
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522 if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossuma3862092002-06-10 15:24:42 +0000523 /* For a heaptype, the instances count as references
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 to the type. Traverse the type so the collector
Guido van Rossuma3862092002-06-10 15:24:42 +0000525 can find cycles involving this link. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000526 Py_VISIT(type);
Guido van Rossuma3862092002-06-10 15:24:42 +0000527
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000528 if (basetraverse)
529 return basetraverse(self, visit, arg);
530 return 0;
531}
532
533static void
534clear_slots(PyTypeObject *type, PyObject *self)
535{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000536 Py_ssize_t i, n;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000537 PyMemberDef *mp;
538
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000539 n = Py_Size(type);
Guido van Rossume5c691a2003-03-07 15:13:17 +0000540 mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000541 for (i = 0; i < n; i++, mp++) {
542 if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
543 char *addr = (char *)self + mp->offset;
544 PyObject *obj = *(PyObject **)addr;
545 if (obj != NULL) {
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000546 *(PyObject **)addr = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000547 Py_DECREF(obj);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000548 }
549 }
550 }
551}
552
553static int
554subtype_clear(PyObject *self)
555{
556 PyTypeObject *type, *base;
557 inquiry baseclear;
558
559 /* Find the nearest base with a different tp_clear
560 and clear slots while we're at it */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000561 type = Py_Type(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000562 base = type;
563 while ((baseclear = base->tp_clear) == subtype_clear) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000564 if (Py_Size(base))
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000565 clear_slots(base, self);
566 base = base->tp_base;
567 assert(base);
568 }
569
Guido van Rossuma3862092002-06-10 15:24:42 +0000570 /* There's no need to clear the instance dict (if any);
571 the collector will call its tp_clear handler. */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000572
573 if (baseclear)
574 return baseclear(self);
Guido van Rossum9475a232001-10-05 20:51:39 +0000575 return 0;
576}
Tim Peters6d6c1a32001-08-02 04:15:00 +0000577
578static void
579subtype_dealloc(PyObject *self)
580{
Guido van Rossum14227b42001-12-06 02:35:58 +0000581 PyTypeObject *type, *base;
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000582 destructor basedealloc;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000583
Guido van Rossum22b13872002-08-06 21:41:44 +0000584 /* Extract the type; we expect it to be a heap type */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000585 type = Py_Type(self);
Guido van Rossum22b13872002-08-06 21:41:44 +0000586 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000587
Guido van Rossum22b13872002-08-06 21:41:44 +0000588 /* Test whether the type has GC exactly once */
589
590 if (!PyType_IS_GC(type)) {
591 /* It's really rare to find a dynamic type that doesn't have
592 GC; it can only happen when deriving from 'object' and not
593 adding any slots or instance variables. This allows
594 certain simplifications: there's no need to call
595 clear_slots(), or DECREF the dict, or clear weakrefs. */
596
597 /* Maybe call finalizer; exit early if resurrected */
Guido van Rossumfebd61d2002-08-08 20:55:20 +0000598 if (type->tp_del) {
599 type->tp_del(self);
600 if (self->ob_refcnt > 0)
601 return;
602 }
Guido van Rossum22b13872002-08-06 21:41:44 +0000603
604 /* Find the nearest base with a different tp_dealloc */
605 base = type;
606 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000607 assert(Py_Size(base) == 0);
Guido van Rossum22b13872002-08-06 21:41:44 +0000608 base = base->tp_base;
609 assert(base);
610 }
611
612 /* Call the base tp_dealloc() */
613 assert(basedealloc);
614 basedealloc(self);
615
616 /* Can't reference self beyond this point */
617 Py_DECREF(type);
618
619 /* Done */
620 return;
621 }
622
623 /* We get here only if the type has GC */
624
625 /* UnTrack and re-Track around the trashcan macro, alas */
Andrew M. Kuchlingc9172d32003-02-06 15:22:49 +0000626 /* See explanation at end of function for full disclosure */
Guido van Rossum0906e072002-08-07 20:42:09 +0000627 PyObject_GC_UnTrack(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000628 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000629 Py_TRASHCAN_SAFE_BEGIN(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000630 --_PyTrash_delete_nesting;
Tim Petersf7f9e992003-11-13 21:59:32 +0000631 /* DO NOT restore GC tracking at this point. weakref callbacks
632 * (if any, and whether directly here or indirectly in something we
633 * call) may trigger GC, and if self is tracked at that point, it
634 * will look like trash to GC and GC will try to delete self again.
Tim Petersadd09b42003-11-12 20:43:28 +0000635 */
Guido van Rossum22b13872002-08-06 21:41:44 +0000636
Guido van Rossum59195fd2003-06-13 20:54:40 +0000637 /* Find the nearest base with a different tp_dealloc */
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000638 base = type;
639 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000640 base = base->tp_base;
641 assert(base);
Guido van Rossum14227b42001-12-06 02:35:58 +0000642 }
643
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 /* If we added a weaklist, we clear it. Do this *before* calling
Guido van Rossum59195fd2003-06-13 20:54:40 +0000645 the finalizer (__del__), clearing slots, or clearing the instance
646 dict. */
647
Guido van Rossum1987c662003-05-29 14:29:23 +0000648 if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
649 PyObject_ClearWeakRefs(self);
650
651 /* Maybe call finalizer; exit early if resurrected */
652 if (type->tp_del) {
Tim Petersf7f9e992003-11-13 21:59:32 +0000653 _PyObject_GC_TRACK(self);
Guido van Rossum1987c662003-05-29 14:29:23 +0000654 type->tp_del(self);
655 if (self->ob_refcnt > 0)
Tim Petersf7f9e992003-11-13 21:59:32 +0000656 goto endlabel; /* resurrected */
657 else
658 _PyObject_GC_UNTRACK(self);
Thomas Woutersb2137042007-02-01 18:02:27 +0000659 /* New weakrefs could be created during the finalizer call.
660 If this occurs, clear them out without calling their
661 finalizers since they might rely on part of the object
662 being finalized that has already been destroyed. */
663 if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
664 /* Modeled after GET_WEAKREFS_LISTPTR() */
665 PyWeakReference **list = (PyWeakReference **) \
666 PyObject_GET_WEAKREFS_LISTPTR(self);
667 while (*list)
668 _PyWeakref_ClearRef(*list);
669 }
Guido van Rossum1987c662003-05-29 14:29:23 +0000670 }
671
Guido van Rossum59195fd2003-06-13 20:54:40 +0000672 /* Clear slots up to the nearest base with a different tp_dealloc */
673 base = type;
674 while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000675 if (Py_Size(base))
Guido van Rossum59195fd2003-06-13 20:54:40 +0000676 clear_slots(base, self);
677 base = base->tp_base;
678 assert(base);
679 }
680
Tim Peters6d6c1a32001-08-02 04:15:00 +0000681 /* If we added a dict, DECREF it */
Guido van Rossum6fb3fde2001-08-30 20:00:07 +0000682 if (type->tp_dictoffset && !base->tp_dictoffset) {
683 PyObject **dictptr = _PyObject_GetDictPtr(self);
684 if (dictptr != NULL) {
685 PyObject *dict = *dictptr;
686 if (dict != NULL) {
687 Py_DECREF(dict);
688 *dictptr = NULL;
689 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000690 }
691 }
692
Tim Peters0bd743c2003-11-13 22:50:00 +0000693 /* Call the base tp_dealloc(); first retrack self if
694 * basedealloc knows about gc.
695 */
696 if (PyType_IS_GC(base))
697 _PyObject_GC_TRACK(self);
Guido van Rossum9923ffe2002-06-04 19:52:53 +0000698 assert(basedealloc);
699 basedealloc(self);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000700
701 /* Can't reference self beyond this point */
Guido van Rossum22b13872002-08-06 21:41:44 +0000702 Py_DECREF(type);
703
Guido van Rossum0906e072002-08-07 20:42:09 +0000704 endlabel:
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000705 ++_PyTrash_delete_nesting;
Guido van Rossum22b13872002-08-06 21:41:44 +0000706 Py_TRASHCAN_SAFE_END(self);
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000707 --_PyTrash_delete_nesting;
708
709 /* Explanation of the weirdness around the trashcan macros:
710
711 Q. What do the trashcan macros do?
712
713 A. Read the comment titled "Trashcan mechanism" in object.h.
714 For one, this explains why there must be a call to GC-untrack
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715 before the trashcan begin macro. Without understanding the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000716 trashcan code, the answers to the following questions don't make
717 sense.
718
719 Q. Why do we GC-untrack before the trashcan and then immediately
720 GC-track again afterward?
721
722 A. In the case that the base class is GC-aware, the base class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723 probably GC-untracks the object. If it does that using the
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000724 UNTRACK macro, this will crash when the object is already
725 untracked. Because we don't know what the base class does, the
726 only safe thing is to make sure the object is tracked when we
727 call the base class dealloc. But... The trashcan begin macro
728 requires that the object is *untracked* before it is called. So
729 the dance becomes:
730
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731 GC untrack
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000732 trashcan begin
733 GC track
734
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735 Q. Why did the last question say "immediately GC-track again"?
736 It's nowhere near immediately.
Tim Petersf7f9e992003-11-13 21:59:32 +0000737
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738 A. Because the code *used* to re-track immediately. Bad Idea.
739 self has a refcount of 0, and if gc ever gets its hands on it
740 (which can happen if any weakref callback gets invoked), it
741 looks like trash to gc too, and gc also tries to delete self
742 then. But we're already deleting self. Double dealloction is
743 a subtle disaster.
Tim Petersf7f9e992003-11-13 21:59:32 +0000744
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000745 Q. Why the bizarre (net-zero) manipulation of
746 _PyTrash_delete_nesting around the trashcan macros?
747
748 A. Some base classes (e.g. list) also use the trashcan mechanism.
749 The following scenario used to be possible:
750
751 - suppose the trashcan level is one below the trashcan limit
752
753 - subtype_dealloc() is called
754
755 - the trashcan limit is not yet reached, so the trashcan level
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 is incremented and the code between trashcan begin and end is
757 executed
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000758
759 - this destroys much of the object's contents, including its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760 slots and __dict__
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000761
762 - basedealloc() is called; this is really list_dealloc(), or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 some other type which also uses the trashcan macros
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000764
765 - the trashcan limit is now reached, so the object is put on the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 trashcan's to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000767
768 - basedealloc() returns
769
770 - subtype_dealloc() decrefs the object's type
771
772 - subtype_dealloc() returns
773
774 - later, the trashcan code starts deleting the objects from its
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775 to-be-deleted-later list
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000776
777 - subtype_dealloc() is called *AGAIN* for the same object
778
779 - at the very least (if the destroyed slots and __dict__ don't
Guido van Rossumd8faa362007-04-27 19:54:29 +0000780 cause problems) the object's type gets decref'ed a second
781 time, which is *BAD*!!!
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000782
783 The remedy is to make sure that if the code between trashcan
784 begin and end in subtype_dealloc() is called, the code between
785 trashcan begin and end in basedealloc() will also be called.
786 This is done by decrementing the level after passing into the
787 trashcan block, and incrementing it just before leaving the
788 block.
789
790 But now it's possible that a chain of objects consisting solely
791 of objects whose deallocator is subtype_dealloc() will defeat
792 the trashcan mechanism completely: the decremented level means
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793 that the effective level never reaches the limit. Therefore, we
Guido van Rossumce8bcd82003-02-05 22:39:45 +0000794 *increment* the level *before* entering the trashcan block, and
795 matchingly decrement it after leaving. This means the trashcan
796 code will trigger a little early, but that's no big deal.
797
798 Q. Are there any live examples of code in need of all this
799 complexity?
800
801 A. Yes. See SF bug 668433 for code that crashed (when Python was
802 compiled in debug mode) before the trashcan level manipulations
803 were added. For more discussion, see SF patches 581742, 575073
804 and bug 574207.
805 */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806}
807
Jeremy Hylton938ace62002-07-17 16:30:39 +0000808static PyTypeObject *solid_base(PyTypeObject *type);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000809
Tim Peters6d6c1a32001-08-02 04:15:00 +0000810/* type test with subclassing support */
811
812int
813PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
814{
815 PyObject *mro;
816
817 mro = a->tp_mro;
818 if (mro != NULL) {
819 /* Deal with multiple inheritance without recursion
820 by walking the MRO tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000821 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000822 assert(PyTuple_Check(mro));
823 n = PyTuple_GET_SIZE(mro);
824 for (i = 0; i < n; i++) {
825 if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
826 return 1;
827 }
828 return 0;
829 }
830 else {
831 /* a is not completely initilized yet; follow tp_base */
832 do {
833 if (a == b)
834 return 1;
835 a = a->tp_base;
836 } while (a != NULL);
837 return b == &PyBaseObject_Type;
838 }
839}
840
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000841/* Internal routines to do a method lookup in the type
Guido van Rossum60718732001-08-28 17:47:51 +0000842 without looking in the instance dictionary
843 (so we can't use PyObject_GetAttr) but still binding
Guido van Rossumd8faa362007-04-27 19:54:29 +0000844 it to the instance. The arguments are the object,
Guido van Rossum60718732001-08-28 17:47:51 +0000845 the method name as a C string, and the address of a
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000846 static variable used to cache the interned Python string.
847
848 Two variants:
849
850 - lookup_maybe() returns NULL without raising an exception
851 when the _PyType_Lookup() call fails;
852
853 - lookup_method() always raises an exception upon errors.
854*/
Guido van Rossum60718732001-08-28 17:47:51 +0000855
856static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000857lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
Guido van Rossum60718732001-08-28 17:47:51 +0000858{
859 PyObject *res;
860
861 if (*attrobj == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000862 *attrobj = PyUnicode_InternFromString(attrstr);
Guido van Rossum60718732001-08-28 17:47:51 +0000863 if (*attrobj == NULL)
864 return NULL;
865 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000866 res = _PyType_Lookup(Py_Type(self), *attrobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000867 if (res != NULL) {
Guido van Rossum60718732001-08-28 17:47:51 +0000868 descrgetfunc f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000869 if ((f = Py_Type(res)->tp_descr_get) == NULL)
Guido van Rossum60718732001-08-28 17:47:51 +0000870 Py_INCREF(res);
871 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000872 res = f(res, self, (PyObject *)(Py_Type(self)));
Guido van Rossum60718732001-08-28 17:47:51 +0000873 }
874 return res;
875}
876
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000877static PyObject *
878lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
879{
880 PyObject *res = lookup_maybe(self, attrstr, attrobj);
881 if (res == NULL && !PyErr_Occurred())
882 PyErr_SetObject(PyExc_AttributeError, *attrobj);
883 return res;
884}
885
Guido van Rossum2730b132001-08-28 18:22:14 +0000886/* A variation of PyObject_CallMethod that uses lookup_method()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000887 instead of PyObject_GetAttrString(). This uses the same convention
Guido van Rossum2730b132001-08-28 18:22:14 +0000888 as lookup_method to cache the interned name string object. */
889
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000890static PyObject *
Guido van Rossum2730b132001-08-28 18:22:14 +0000891call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
892{
893 va_list va;
894 PyObject *args, *func = 0, *retval;
Guido van Rossum2730b132001-08-28 18:22:14 +0000895 va_start(va, format);
896
Guido van Rossumda21c012001-10-03 00:50:18 +0000897 func = lookup_maybe(o, name, nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000898 if (func == NULL) {
899 va_end(va);
900 if (!PyErr_Occurred())
Guido van Rossumda21c012001-10-03 00:50:18 +0000901 PyErr_SetObject(PyExc_AttributeError, *nameobj);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000902 return NULL;
903 }
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000904
905 if (format && *format)
906 args = Py_VaBuildValue(format, va);
907 else
908 args = PyTuple_New(0);
909
910 va_end(va);
911
912 if (args == NULL)
913 return NULL;
914
915 assert(PyTuple_Check(args));
916 retval = PyObject_Call(func, args, NULL);
917
918 Py_DECREF(args);
919 Py_DECREF(func);
920
921 return retval;
922}
923
924/* Clone of call_method() that returns NotImplemented when the lookup fails. */
925
Neil Schemenauerf23473f2001-10-21 22:28:58 +0000926static PyObject *
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000927call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
928{
929 va_list va;
930 PyObject *args, *func = 0, *retval;
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000931 va_start(va, format);
932
Guido van Rossumda21c012001-10-03 00:50:18 +0000933 func = lookup_maybe(o, name, nameobj);
Guido van Rossum2730b132001-08-28 18:22:14 +0000934 if (func == NULL) {
935 va_end(va);
Guido van Rossumf21c6be2001-09-14 17:51:50 +0000936 if (!PyErr_Occurred()) {
937 Py_INCREF(Py_NotImplemented);
938 return Py_NotImplemented;
939 }
Guido van Rossum717ce002001-09-14 16:58:08 +0000940 return NULL;
Guido van Rossum2730b132001-08-28 18:22:14 +0000941 }
942
943 if (format && *format)
944 args = Py_VaBuildValue(format, va);
945 else
946 args = PyTuple_New(0);
947
948 va_end(va);
949
Guido van Rossum717ce002001-09-14 16:58:08 +0000950 if (args == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +0000951 return NULL;
952
Guido van Rossum717ce002001-09-14 16:58:08 +0000953 assert(PyTuple_Check(args));
954 retval = PyObject_Call(func, args, NULL);
Guido van Rossum2730b132001-08-28 18:22:14 +0000955
956 Py_DECREF(args);
957 Py_DECREF(func);
958
959 return retval;
960}
961
Tim Petersea7f75d2002-12-07 21:39:16 +0000962/*
Guido van Rossum1f121312002-11-14 19:49:16 +0000963 Method resolution order algorithm C3 described in
964 "A Monotonic Superclass Linearization for Dylan",
965 by Kim Barrett, Bob Cassel, Paul Haahr,
Tim Petersea7f75d2002-12-07 21:39:16 +0000966 David A. Moon, Keith Playford, and P. Tucker Withington.
Guido van Rossum1f121312002-11-14 19:49:16 +0000967 (OOPSLA 1996)
968
Guido van Rossum98f33732002-11-25 21:36:54 +0000969 Some notes about the rules implied by C3:
970
Tim Petersea7f75d2002-12-07 21:39:16 +0000971 No duplicate bases.
Guido van Rossum98f33732002-11-25 21:36:54 +0000972 It isn't legal to repeat a class in a list of base classes.
973
974 The next three properties are the 3 constraints in "C3".
975
Tim Petersea7f75d2002-12-07 21:39:16 +0000976 Local precendece order.
Guido van Rossum98f33732002-11-25 21:36:54 +0000977 If A precedes B in C's MRO, then A will precede B in the MRO of all
978 subclasses of C.
979
980 Monotonicity.
981 The MRO of a class must be an extension without reordering of the
982 MRO of each of its superclasses.
983
984 Extended Precedence Graph (EPG).
985 Linearization is consistent if there is a path in the EPG from
986 each class to all its successors in the linearization. See
987 the paper for definition of EPG.
Guido van Rossum1f121312002-11-14 19:49:16 +0000988 */
989
Tim Petersea7f75d2002-12-07 21:39:16 +0000990static int
Guido van Rossum1f121312002-11-14 19:49:16 +0000991tail_contains(PyObject *list, int whence, PyObject *o) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000992 Py_ssize_t j, size;
Guido van Rossum1f121312002-11-14 19:49:16 +0000993 size = PyList_GET_SIZE(list);
994
995 for (j = whence+1; j < size; j++) {
996 if (PyList_GET_ITEM(list, j) == o)
997 return 1;
998 }
999 return 0;
1000}
1001
Guido van Rossum98f33732002-11-25 21:36:54 +00001002static PyObject *
1003class_name(PyObject *cls)
1004{
1005 PyObject *name = PyObject_GetAttrString(cls, "__name__");
1006 if (name == NULL) {
1007 PyErr_Clear();
1008 Py_XDECREF(name);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001009 name = PyObject_ReprStr8(cls);
Guido van Rossum98f33732002-11-25 21:36:54 +00001010 }
1011 if (name == NULL)
1012 return NULL;
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001013 if (!PyUnicode_Check(name)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001014 Py_DECREF(name);
1015 return NULL;
1016 }
1017 return name;
1018}
1019
1020static int
1021check_duplicates(PyObject *list)
1022{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001023 Py_ssize_t i, j, n;
Guido van Rossum98f33732002-11-25 21:36:54 +00001024 /* Let's use a quadratic time algorithm,
1025 assuming that the bases lists is short.
1026 */
1027 n = PyList_GET_SIZE(list);
1028 for (i = 0; i < n; i++) {
1029 PyObject *o = PyList_GET_ITEM(list, i);
1030 for (j = i + 1; j < n; j++) {
1031 if (PyList_GET_ITEM(list, j) == o) {
1032 o = class_name(o);
1033 PyErr_Format(PyExc_TypeError,
1034 "duplicate base class %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001035 o ? PyUnicode_AsString(o) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001036 Py_XDECREF(o);
1037 return -1;
1038 }
1039 }
1040 }
1041 return 0;
1042}
1043
1044/* Raise a TypeError for an MRO order disagreement.
1045
1046 It's hard to produce a good error message. In the absence of better
1047 insight into error reporting, report the classes that were candidates
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 to be put next into the MRO. There is some conflict between the
Guido van Rossum98f33732002-11-25 21:36:54 +00001049 order in which they should be put in the MRO, but it's hard to
1050 diagnose what constraint can't be satisfied.
1051*/
1052
1053static void
1054set_mro_error(PyObject *to_merge, int *remain)
1055{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001056 Py_ssize_t i, n, off, to_merge_size;
Guido van Rossum98f33732002-11-25 21:36:54 +00001057 char buf[1000];
1058 PyObject *k, *v;
1059 PyObject *set = PyDict_New();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001060 if (!set) return;
Guido van Rossum98f33732002-11-25 21:36:54 +00001061
1062 to_merge_size = PyList_GET_SIZE(to_merge);
1063 for (i = 0; i < to_merge_size; i++) {
1064 PyObject *L = PyList_GET_ITEM(to_merge, i);
1065 if (remain[i] < PyList_GET_SIZE(L)) {
1066 PyObject *c = PyList_GET_ITEM(L, remain[i]);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001067 if (PyDict_SetItem(set, c, Py_None) < 0) {
1068 Py_DECREF(set);
Guido van Rossum98f33732002-11-25 21:36:54 +00001069 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001070 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001071 }
1072 }
1073 n = PyDict_Size(set);
1074
Raymond Hettingerf394df42003-04-06 19:13:41 +00001075 off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
1076consistent method resolution\norder (MRO) for bases");
Guido van Rossum98f33732002-11-25 21:36:54 +00001077 i = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001078 while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001079 PyObject *name = class_name(k);
1080 off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
Martin v. Löwis9b9905b2007-06-10 21:13:34 +00001081 name ? PyUnicode_AsString(name) : "?");
Guido van Rossum98f33732002-11-25 21:36:54 +00001082 Py_XDECREF(name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001083 if (--n && (size_t)(off+1) < sizeof(buf)) {
Guido van Rossum98f33732002-11-25 21:36:54 +00001084 buf[off++] = ',';
1085 buf[off] = '\0';
1086 }
1087 }
1088 PyErr_SetString(PyExc_TypeError, buf);
1089 Py_DECREF(set);
1090}
1091
Tim Petersea7f75d2002-12-07 21:39:16 +00001092static int
Guido van Rossum1f121312002-11-14 19:49:16 +00001093pmerge(PyObject *acc, PyObject* to_merge) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001094 Py_ssize_t i, j, to_merge_size, empty_cnt;
Guido van Rossum1f121312002-11-14 19:49:16 +00001095 int *remain;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096 int ok;
Tim Petersea7f75d2002-12-07 21:39:16 +00001097
Guido van Rossum1f121312002-11-14 19:49:16 +00001098 to_merge_size = PyList_GET_SIZE(to_merge);
1099
Guido van Rossum98f33732002-11-25 21:36:54 +00001100 /* remain stores an index into each sublist of to_merge.
1101 remain[i] is the index of the next base in to_merge[i]
1102 that is not included in acc.
1103 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104 remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
Guido van Rossum1f121312002-11-14 19:49:16 +00001105 if (remain == NULL)
1106 return -1;
1107 for (i = 0; i < to_merge_size; i++)
1108 remain[i] = 0;
1109
1110 again:
1111 empty_cnt = 0;
1112 for (i = 0; i < to_merge_size; i++) {
1113 PyObject *candidate;
Tim Petersea7f75d2002-12-07 21:39:16 +00001114
Guido van Rossum1f121312002-11-14 19:49:16 +00001115 PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1116
1117 if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1118 empty_cnt++;
1119 continue;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001121
Guido van Rossum98f33732002-11-25 21:36:54 +00001122 /* Choose next candidate for MRO.
1123
1124 The input sequences alone can determine the choice.
1125 If not, choose the class which appears in the MRO
1126 of the earliest direct superclass of the new class.
1127 */
1128
Guido van Rossum1f121312002-11-14 19:49:16 +00001129 candidate = PyList_GET_ITEM(cur_list, remain[i]);
1130 for (j = 0; j < to_merge_size; j++) {
1131 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum98f33732002-11-25 21:36:54 +00001132 if (tail_contains(j_lst, remain[j], candidate)) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001133 goto skip; /* continue outer loop */
Guido van Rossum98f33732002-11-25 21:36:54 +00001134 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001135 }
1136 ok = PyList_Append(acc, candidate);
1137 if (ok < 0) {
1138 PyMem_Free(remain);
1139 return -1;
1140 }
1141 for (j = 0; j < to_merge_size; j++) {
1142 PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
Guido van Rossum768158c2002-12-31 16:33:01 +00001143 if (remain[j] < PyList_GET_SIZE(j_lst) &&
1144 PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001145 remain[j]++;
1146 }
1147 }
1148 goto again;
Tim Peters9a6b8d82002-11-14 23:22:33 +00001149 skip: ;
Guido van Rossum1f121312002-11-14 19:49:16 +00001150 }
1151
Guido van Rossum98f33732002-11-25 21:36:54 +00001152 if (empty_cnt == to_merge_size) {
1153 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001154 return 0;
Guido van Rossum98f33732002-11-25 21:36:54 +00001155 }
1156 set_mro_error(to_merge, remain);
1157 PyMem_FREE(remain);
Guido van Rossum1f121312002-11-14 19:49:16 +00001158 return -1;
1159}
1160
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161static PyObject *
1162mro_implementation(PyTypeObject *type)
1163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164 Py_ssize_t i, n;
1165 int ok;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166 PyObject *bases, *result;
Guido van Rossum1f121312002-11-14 19:49:16 +00001167 PyObject *to_merge, *bases_aslist;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168
Guido van Rossum63517572002-06-18 16:44:57 +00001169 if(type->tp_dict == NULL) {
1170 if(PyType_Ready(type) < 0)
1171 return NULL;
1172 }
1173
Guido van Rossum98f33732002-11-25 21:36:54 +00001174 /* Find a superclass linearization that honors the constraints
1175 of the explicit lists of bases and the constraints implied by
Tim Petersea7f75d2002-12-07 21:39:16 +00001176 each base class.
Guido van Rossum98f33732002-11-25 21:36:54 +00001177
1178 to_merge is a list of lists, where each list is a superclass
1179 linearization implied by a base class. The last element of
1180 to_merge is the declared list of bases.
1181 */
1182
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 bases = type->tp_bases;
1184 n = PyTuple_GET_SIZE(bases);
Guido van Rossum1f121312002-11-14 19:49:16 +00001185
1186 to_merge = PyList_New(n+1);
1187 if (to_merge == NULL)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 return NULL;
Guido van Rossum1f121312002-11-14 19:49:16 +00001189
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001191 PyObject *base = PyTuple_GET_ITEM(bases, i);
1192 PyObject *parentMRO;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001193 parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 if (parentMRO == NULL) {
Guido van Rossum1f121312002-11-14 19:49:16 +00001195 Py_DECREF(to_merge);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001197 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001198
1199 PyList_SET_ITEM(to_merge, i, parentMRO);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001201
1202 bases_aslist = PySequence_List(bases);
1203 if (bases_aslist == NULL) {
1204 Py_DECREF(to_merge);
1205 return NULL;
1206 }
Guido van Rossum98f33732002-11-25 21:36:54 +00001207 /* This is just a basic sanity check. */
1208 if (check_duplicates(bases_aslist) < 0) {
1209 Py_DECREF(to_merge);
1210 Py_DECREF(bases_aslist);
1211 return NULL;
1212 }
Guido van Rossum1f121312002-11-14 19:49:16 +00001213 PyList_SET_ITEM(to_merge, n, bases_aslist);
1214
1215 result = Py_BuildValue("[O]", (PyObject *)type);
1216 if (result == NULL) {
1217 Py_DECREF(to_merge);
1218 return NULL;
1219 }
1220
1221 ok = pmerge(result, to_merge);
1222 Py_DECREF(to_merge);
1223 if (ok < 0) {
1224 Py_DECREF(result);
1225 return NULL;
1226 }
1227
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 return result;
1229}
1230
1231static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001232mro_external(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233{
1234 PyTypeObject *type = (PyTypeObject *)self;
1235
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 return mro_implementation(type);
1237}
1238
1239static int
1240mro_internal(PyTypeObject *type)
1241{
1242 PyObject *mro, *result, *tuple;
Armin Rigo037d1e02005-12-29 17:07:39 +00001243 int checkit = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001245 if (Py_Type(type) == &PyType_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 result = mro_implementation(type);
1247 }
1248 else {
Guido van Rossum60718732001-08-28 17:47:51 +00001249 static PyObject *mro_str;
Armin Rigo037d1e02005-12-29 17:07:39 +00001250 checkit = 1;
Guido van Rossum60718732001-08-28 17:47:51 +00001251 mro = lookup_method((PyObject *)type, "mro", &mro_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001252 if (mro == NULL)
1253 return -1;
1254 result = PyObject_CallObject(mro, NULL);
1255 Py_DECREF(mro);
1256 }
1257 if (result == NULL)
1258 return -1;
1259 tuple = PySequence_Tuple(result);
1260 Py_DECREF(result);
Armin Rigo037d1e02005-12-29 17:07:39 +00001261 if (tuple == NULL)
1262 return -1;
1263 if (checkit) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001264 Py_ssize_t i, len;
Armin Rigo037d1e02005-12-29 17:07:39 +00001265 PyObject *cls;
1266 PyTypeObject *solid;
1267
1268 solid = solid_base(type);
1269
1270 len = PyTuple_GET_SIZE(tuple);
1271
1272 for (i = 0; i < len; i++) {
1273 PyTypeObject *t;
1274 cls = PyTuple_GET_ITEM(tuple, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001275 if (!PyType_Check(cls)) {
Armin Rigo037d1e02005-12-29 17:07:39 +00001276 PyErr_Format(PyExc_TypeError,
1277 "mro() returned a non-class ('%.500s')",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001278 Py_Type(cls)->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001279 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001280 return -1;
1281 }
1282 t = (PyTypeObject*)cls;
1283 if (!PyType_IsSubtype(solid, solid_base(t))) {
1284 PyErr_Format(PyExc_TypeError,
1285 "mro() returned base with unsuitable layout ('%.500s')",
1286 t->tp_name);
Neal Norwitz50bf51a2006-01-02 02:46:54 +00001287 Py_DECREF(tuple);
Armin Rigo037d1e02005-12-29 17:07:39 +00001288 return -1;
1289 }
1290 }
1291 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 type->tp_mro = tuple;
1293 return 0;
1294}
1295
1296
1297/* Calculate the best base amongst multiple base classes.
1298 This is the first one that's on the path to the "solid base". */
1299
1300static PyTypeObject *
1301best_base(PyObject *bases)
1302{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001303 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 PyTypeObject *base, *winner, *candidate, *base_i;
Tim Petersa91e9642001-11-14 23:32:33 +00001305 PyObject *base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306
1307 assert(PyTuple_Check(bases));
1308 n = PyTuple_GET_SIZE(bases);
1309 assert(n > 0);
Tim Petersa91e9642001-11-14 23:32:33 +00001310 base = NULL;
1311 winner = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00001313 base_proto = PyTuple_GET_ITEM(bases, i);
Tim Petersa91e9642001-11-14 23:32:33 +00001314 if (!PyType_Check(base_proto)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 PyErr_SetString(
1316 PyExc_TypeError,
1317 "bases must be types");
1318 return NULL;
1319 }
Tim Petersa91e9642001-11-14 23:32:33 +00001320 base_i = (PyTypeObject *)base_proto;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 if (base_i->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001322 if (PyType_Ready(base_i) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 return NULL;
1324 }
1325 candidate = solid_base(base_i);
Tim Petersa91e9642001-11-14 23:32:33 +00001326 if (winner == NULL) {
1327 winner = candidate;
1328 base = base_i;
1329 }
1330 else if (PyType_IsSubtype(winner, candidate))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 ;
1332 else if (PyType_IsSubtype(candidate, winner)) {
1333 winner = candidate;
1334 base = base_i;
1335 }
1336 else {
1337 PyErr_SetString(
1338 PyExc_TypeError,
1339 "multiple bases have "
1340 "instance lay-out conflict");
1341 return NULL;
1342 }
1343 }
Guido van Rossume54616c2001-12-14 04:19:56 +00001344 if (base == NULL)
1345 PyErr_SetString(PyExc_TypeError,
1346 "a new-style class can't have only classic bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347 return base;
1348}
1349
1350static int
1351extra_ivars(PyTypeObject *type, PyTypeObject *base)
1352{
Neil Schemenauerc806c882001-08-29 23:54:54 +00001353 size_t t_size = type->tp_basicsize;
1354 size_t b_size = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355
Guido van Rossum9676b222001-08-17 20:32:36 +00001356 assert(t_size >= b_size); /* Else type smaller than base! */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357 if (type->tp_itemsize || base->tp_itemsize) {
1358 /* If itemsize is involved, stricter rules */
1359 return t_size != b_size ||
1360 type->tp_itemsize != base->tp_itemsize;
1361 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001362 if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001363 type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
1364 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001365 t_size -= sizeof(PyObject *);
1366 if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
Guido van Rossum360e4b82007-05-14 22:51:27 +00001367 type->tp_dictoffset + sizeof(PyObject *) == t_size &&
1368 type->tp_flags & Py_TPFLAGS_HEAPTYPE)
Guido van Rossum9676b222001-08-17 20:32:36 +00001369 t_size -= sizeof(PyObject *);
1370
1371 return t_size != b_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372}
1373
1374static PyTypeObject *
1375solid_base(PyTypeObject *type)
1376{
1377 PyTypeObject *base;
1378
1379 if (type->tp_base)
1380 base = solid_base(type->tp_base);
1381 else
1382 base = &PyBaseObject_Type;
1383 if (extra_ivars(type, base))
1384 return type;
1385 else
1386 return base;
1387}
1388
Jeremy Hylton938ace62002-07-17 16:30:39 +00001389static void object_dealloc(PyObject *);
1390static int object_init(PyObject *, PyObject *, PyObject *);
1391static int update_slot(PyTypeObject *, PyObject *);
1392static void fixup_slot_dispatchers(PyTypeObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393
Guido van Rossum360e4b82007-05-14 22:51:27 +00001394/*
1395 * Helpers for __dict__ descriptor. We don't want to expose the dicts
1396 * inherited from various builtin types. The builtin base usually provides
1397 * its own __dict__ descriptor, so we use that when we can.
1398 */
1399static PyTypeObject *
1400get_builtin_base_with_dict(PyTypeObject *type)
1401{
1402 while (type->tp_base != NULL) {
1403 if (type->tp_dictoffset != 0 &&
1404 !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
1405 return type;
1406 type = type->tp_base;
1407 }
1408 return NULL;
1409}
1410
1411static PyObject *
1412get_dict_descriptor(PyTypeObject *type)
1413{
1414 static PyObject *dict_str;
1415 PyObject *descr;
1416
1417 if (dict_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001418 dict_str = PyUnicode_InternFromString("__dict__");
Guido van Rossum360e4b82007-05-14 22:51:27 +00001419 if (dict_str == NULL)
1420 return NULL;
1421 }
1422 descr = _PyType_Lookup(type, dict_str);
1423 if (descr == NULL || !PyDescr_IsData(descr))
1424 return NULL;
1425
1426 return descr;
1427}
1428
1429static void
1430raise_dict_descr_error(PyObject *obj)
1431{
1432 PyErr_Format(PyExc_TypeError,
1433 "this __dict__ descriptor does not support "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001434 "'%.200s' objects", Py_Type(obj)->tp_name);
Guido van Rossum360e4b82007-05-14 22:51:27 +00001435}
1436
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437static PyObject *
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001438subtype_dict(PyObject *obj, void *context)
1439{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001440 PyObject **dictptr;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001441 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001442 PyTypeObject *base;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001443
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001444 base = get_builtin_base_with_dict(Py_Type(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001445 if (base != NULL) {
1446 descrgetfunc func;
1447 PyObject *descr = get_dict_descriptor(base);
1448 if (descr == NULL) {
1449 raise_dict_descr_error(obj);
1450 return NULL;
1451 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001452 func = Py_Type(descr)->tp_descr_get;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001453 if (func == NULL) {
1454 raise_dict_descr_error(obj);
1455 return NULL;
1456 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001457 return func(descr, obj, (PyObject *)(Py_Type(obj)));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001458 }
1459
1460 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001461 if (dictptr == NULL) {
1462 PyErr_SetString(PyExc_AttributeError,
1463 "This object has no __dict__");
1464 return NULL;
1465 }
1466 dict = *dictptr;
Guido van Rossum3926a632001-09-25 16:25:58 +00001467 if (dict == NULL)
1468 *dictptr = dict = PyDict_New();
1469 Py_XINCREF(dict);
1470 return dict;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001471}
1472
Guido van Rossum6661be32001-10-26 04:26:12 +00001473static int
1474subtype_setdict(PyObject *obj, PyObject *value, void *context)
1475{
Guido van Rossum360e4b82007-05-14 22:51:27 +00001476 PyObject **dictptr;
Guido van Rossum6661be32001-10-26 04:26:12 +00001477 PyObject *dict;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001478 PyTypeObject *base;
Guido van Rossum6661be32001-10-26 04:26:12 +00001479
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001480 base = get_builtin_base_with_dict(Py_Type(obj));
Guido van Rossum360e4b82007-05-14 22:51:27 +00001481 if (base != NULL) {
1482 descrsetfunc func;
1483 PyObject *descr = get_dict_descriptor(base);
1484 if (descr == NULL) {
1485 raise_dict_descr_error(obj);
1486 return -1;
1487 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001488 func = Py_Type(descr)->tp_descr_set;
Guido van Rossum360e4b82007-05-14 22:51:27 +00001489 if (func == NULL) {
1490 raise_dict_descr_error(obj);
1491 return -1;
1492 }
1493 return func(descr, obj, value);
1494 }
1495
1496 dictptr = _PyObject_GetDictPtr(obj);
Guido van Rossum6661be32001-10-26 04:26:12 +00001497 if (dictptr == NULL) {
1498 PyErr_SetString(PyExc_AttributeError,
1499 "This object has no __dict__");
1500 return -1;
1501 }
Guido van Rossumd331cb52001-12-05 19:46:42 +00001502 if (value != NULL && !PyDict_Check(value)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001503 PyErr_Format(PyExc_TypeError,
1504 "__dict__ must be set to a dictionary, "
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001505 "not a '%.200s'", Py_Type(value)->tp_name);
Guido van Rossum6661be32001-10-26 04:26:12 +00001506 return -1;
1507 }
1508 dict = *dictptr;
Guido van Rossumd331cb52001-12-05 19:46:42 +00001509 Py_XINCREF(value);
Guido van Rossum6661be32001-10-26 04:26:12 +00001510 *dictptr = value;
1511 Py_XDECREF(dict);
1512 return 0;
1513}
1514
Guido van Rossumad47da02002-08-12 19:05:44 +00001515static PyObject *
1516subtype_getweakref(PyObject *obj, void *context)
1517{
1518 PyObject **weaklistptr;
1519 PyObject *result;
1520
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001521 if (Py_Type(obj)->tp_weaklistoffset == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001522 PyErr_SetString(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001523 "This object has no __weakref__");
Guido van Rossumad47da02002-08-12 19:05:44 +00001524 return NULL;
1525 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001526 assert(Py_Type(obj)->tp_weaklistoffset > 0);
1527 assert(Py_Type(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
1528 (size_t)(Py_Type(obj)->tp_basicsize));
Guido van Rossumad47da02002-08-12 19:05:44 +00001529 weaklistptr = (PyObject **)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001530 ((char *)obj + Py_Type(obj)->tp_weaklistoffset);
Guido van Rossumad47da02002-08-12 19:05:44 +00001531 if (*weaklistptr == NULL)
1532 result = Py_None;
1533 else
1534 result = *weaklistptr;
1535 Py_INCREF(result);
1536 return result;
1537}
1538
Guido van Rossum373c7412003-01-07 13:41:37 +00001539/* Three variants on the subtype_getsets list. */
1540
1541static PyGetSetDef subtype_getsets_full[] = {
Guido van Rossumad47da02002-08-12 19:05:44 +00001542 {"__dict__", subtype_dict, subtype_setdict,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001543 PyDoc_STR("dictionary for instance variables (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001544 {"__weakref__", subtype_getweakref, NULL,
Neal Norwitz858e34f2002-08-13 17:18:45 +00001545 PyDoc_STR("list of weak references to the object (if defined)")},
Guido van Rossumad47da02002-08-12 19:05:44 +00001546 {0}
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001547};
1548
Guido van Rossum373c7412003-01-07 13:41:37 +00001549static PyGetSetDef subtype_getsets_dict_only[] = {
1550 {"__dict__", subtype_dict, subtype_setdict,
1551 PyDoc_STR("dictionary for instance variables (if defined)")},
1552 {0}
1553};
1554
1555static PyGetSetDef subtype_getsets_weakref_only[] = {
1556 {"__weakref__", subtype_getweakref, NULL,
1557 PyDoc_STR("list of weak references to the object (if defined)")},
1558 {0}
1559};
1560
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001561static int
1562valid_identifier(PyObject *s)
1563{
Martin v. Löwis5b222132007-06-10 09:51:05 +00001564 if (!PyUnicode_Check(s)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001565 PyErr_Format(PyExc_TypeError,
1566 "__slots__ items must be strings, not '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001567 Py_Type(s)->tp_name);
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001568 return 0;
1569 }
Georg Brandlf4780d02007-08-30 18:29:48 +00001570 if (!PyUnicode_IsIdentifier(s)) {
1571 PyErr_SetString(PyExc_TypeError,
1572 "__slots__ must be identifiers");
1573 return 0;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001574 }
1575 return 1;
1576}
1577
Guido van Rossumd8faa362007-04-27 19:54:29 +00001578/* Forward */
1579static int
1580object_init(PyObject *self, PyObject *args, PyObject *kwds);
1581
1582static int
1583type_init(PyObject *cls, PyObject *args, PyObject *kwds)
1584{
1585 int res;
1586
1587 assert(args != NULL && PyTuple_Check(args));
1588 assert(kwds == NULL || PyDict_Check(kwds));
1589
1590 if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
1591 PyErr_SetString(PyExc_TypeError,
1592 "type.__init__() takes no keyword arguments");
1593 return -1;
1594 }
1595
1596 if (args != NULL && PyTuple_Check(args) &&
1597 (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
1598 PyErr_SetString(PyExc_TypeError,
1599 "type.__init__() takes 1 or 3 arguments");
1600 return -1;
1601 }
1602
1603 /* Call object.__init__(self) now. */
1604 /* XXX Could call super(type, cls).__init__() but what's the point? */
1605 args = PyTuple_GetSlice(args, 0, 0);
1606 res = object_init(cls, args, NULL);
1607 Py_DECREF(args);
1608 return res;
1609}
1610
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001611static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001612type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1613{
1614 PyObject *name, *bases, *dict;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001615 static char *kwlist[] = {"name", "bases", "dict", 0};
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001616 PyObject *slots, *tmp, *newslots;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001617 PyTypeObject *type, *base, *tmptype, *winner;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001618 PyHeapTypeObject *et;
Guido van Rossum6f799372001-09-20 20:46:19 +00001619 PyMemberDef *mp;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001620 Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
Guido van Rossumad47da02002-08-12 19:05:44 +00001621 int j, may_add_dict, may_add_weak;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001622
Tim Peters3abca122001-10-27 19:37:48 +00001623 assert(args != NULL && PyTuple_Check(args));
1624 assert(kwds == NULL || PyDict_Check(kwds));
1625
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001626 /* Special case: type(x) should return x->ob_type */
Tim Peters3abca122001-10-27 19:37:48 +00001627 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001628 const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
1629 const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
Tim Peters3abca122001-10-27 19:37:48 +00001630
1631 if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1632 PyObject *x = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001633 Py_INCREF(Py_Type(x));
1634 return (PyObject *) Py_Type(x);
Tim Peters3abca122001-10-27 19:37:48 +00001635 }
1636
1637 /* SF bug 475327 -- if that didn't trigger, we need 3
1638 arguments. but PyArg_ParseTupleAndKeywords below may give
1639 a msg saying type() needs exactly 3. */
1640 if (nargs + nkwds != 3) {
1641 PyErr_SetString(PyExc_TypeError,
1642 "type() takes 1 or 3 arguments");
1643 return NULL;
1644 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 }
1646
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001647 /* Check arguments: (name, bases, dict) */
Thomas Hellerace8ba82007-07-11 20:01:43 +00001648 if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001649 &name,
1650 &PyTuple_Type, &bases,
1651 &PyDict_Type, &dict))
1652 return NULL;
1653
1654 /* Determine the proper metatype to deal with this,
1655 and check for metatype conflicts while we're at it.
1656 Note that if some other metatype wins to contract,
1657 it's possible that its instances are not types. */
1658 nbases = PyTuple_GET_SIZE(bases);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001659 winner = metatype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001660 for (i = 0; i < nbases; i++) {
1661 tmp = PyTuple_GET_ITEM(bases, i);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001662 tmptype = Py_Type(tmp);
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001663 if (PyType_IsSubtype(winner, tmptype))
Tim Peters6d6c1a32001-08-02 04:15:00 +00001664 continue;
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001665 if (PyType_IsSubtype(tmptype, winner)) {
1666 winner = tmptype;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 continue;
1668 }
1669 PyErr_SetString(PyExc_TypeError,
Guido van Rossum636688d2003-04-23 12:07:22 +00001670 "metaclass conflict: "
1671 "the metaclass of a derived class "
1672 "must be a (non-strict) subclass "
1673 "of the metaclasses of all its bases");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001674 return NULL;
1675 }
Guido van Rossum8d32c8b2001-08-17 11:18:38 +00001676 if (winner != metatype) {
1677 if (winner->tp_new != type_new) /* Pass it to the winner */
1678 return winner->tp_new(winner, args, kwds);
1679 metatype = winner;
1680 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681
1682 /* Adjust for empty tuple bases */
1683 if (nbases == 0) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001684 bases = PyTuple_Pack(1, &PyBaseObject_Type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001685 if (bases == NULL)
1686 return NULL;
1687 nbases = 1;
1688 }
1689 else
1690 Py_INCREF(bases);
1691
1692 /* XXX From here until type is allocated, "return NULL" leaks bases! */
1693
1694 /* Calculate best base, and check that all bases are type objects */
1695 base = best_base(bases);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001696 if (base == NULL) {
1697 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001698 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001699 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001700 if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1701 PyErr_Format(PyExc_TypeError,
1702 "type '%.100s' is not an acceptable base type",
1703 base->tp_name);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001704 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 return NULL;
1706 }
1707
Tim Peters6d6c1a32001-08-02 04:15:00 +00001708 /* Check for a __slots__ sequence variable in dict, and count it */
1709 slots = PyDict_GetItemString(dict, "__slots__");
1710 nslots = 0;
Guido van Rossum9676b222001-08-17 20:32:36 +00001711 add_dict = 0;
1712 add_weak = 0;
Guido van Rossumad47da02002-08-12 19:05:44 +00001713 may_add_dict = base->tp_dictoffset == 0;
1714 may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1715 if (slots == NULL) {
1716 if (may_add_dict) {
1717 add_dict++;
1718 }
1719 if (may_add_weak) {
1720 add_weak++;
1721 }
1722 }
1723 else {
1724 /* Have slots */
1725
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726 /* Make it into a tuple */
Neal Norwitz80e7f272007-08-26 06:45:23 +00001727 if (PyUnicode_Check(slots))
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001728 slots = PyTuple_Pack(1, slots);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729 else
1730 slots = PySequence_Tuple(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001731 if (slots == NULL) {
1732 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001733 return NULL;
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001734 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001735 assert(PyTuple_Check(slots));
1736
1737 /* Are slots allowed? */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001738 nslots = PyTuple_GET_SIZE(slots);
Jeremy Hylton1c7a0ea2003-07-16 16:08:23 +00001739 if (nslots > 0 && base->tp_itemsize != 0) {
Guido van Rossumc4141872001-08-30 04:43:35 +00001740 PyErr_Format(PyExc_TypeError,
1741 "nonempty __slots__ "
1742 "not supported for subtype of '%s'",
1743 base->tp_name);
Guido van Rossumad47da02002-08-12 19:05:44 +00001744 bad_slots:
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001745 Py_DECREF(bases);
Guido van Rossumad47da02002-08-12 19:05:44 +00001746 Py_DECREF(slots);
Guido van Rossumc4141872001-08-30 04:43:35 +00001747 return NULL;
1748 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001749
1750 /* Check for valid slot names and two special cases */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001751 for (i = 0; i < nslots; i++) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001752 PyObject *tmp = PyTuple_GET_ITEM(slots, i);
Guido van Rossumad47da02002-08-12 19:05:44 +00001753 if (!valid_identifier(tmp))
1754 goto bad_slots;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001755 assert(PyUnicode_Check(tmp));
1756 if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001757 if (!may_add_dict || add_dict) {
1758 PyErr_SetString(PyExc_TypeError,
1759 "__dict__ slot disallowed: "
1760 "we already got one");
1761 goto bad_slots;
1762 }
1763 add_dict++;
1764 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00001765 if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
Guido van Rossumad47da02002-08-12 19:05:44 +00001766 if (!may_add_weak || add_weak) {
1767 PyErr_SetString(PyExc_TypeError,
1768 "__weakref__ slot disallowed: "
1769 "either we already got one, "
1770 "or __itemsize__ != 0");
1771 goto bad_slots;
1772 }
1773 add_weak++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001774 }
1775 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001776
Guido van Rossumd8faa362007-04-27 19:54:29 +00001777 /* Copy slots into a list, mangle names and sort them.
1778 Sorted names are needed for __class__ assignment.
1779 Convert them back to tuple at the end.
1780 */
1781 newslots = PyList_New(nslots - add_dict - add_weak);
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001782 if (newslots == NULL)
Guido van Rossumad47da02002-08-12 19:05:44 +00001783 goto bad_slots;
1784 for (i = j = 0; i < nslots; i++) {
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001785 tmp = PyTuple_GET_ITEM(slots, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001786 if ((add_dict &&
1787 PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) ||
1788 (add_weak &&
1789 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
Guido van Rossumad47da02002-08-12 19:05:44 +00001790 continue;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 tmp =_Py_Mangle(name, tmp);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001792 if (!tmp)
1793 goto bad_slots;
1794 PyList_SET_ITEM(newslots, j, tmp);
Guido van Rossumad47da02002-08-12 19:05:44 +00001795 j++;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001796 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001797 assert(j == nslots - add_dict - add_weak);
1798 nslots = j;
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001799 Py_DECREF(slots);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001800 if (PyList_Sort(newslots) == -1) {
1801 Py_DECREF(bases);
1802 Py_DECREF(newslots);
1803 return NULL;
1804 }
1805 slots = PyList_AsTuple(newslots);
1806 Py_DECREF(newslots);
1807 if (slots == NULL) {
1808 Py_DECREF(bases);
1809 return NULL;
1810 }
Raymond Hettinger0ae0c072002-06-20 22:23:15 +00001811
Guido van Rossumad47da02002-08-12 19:05:44 +00001812 /* Secondary bases may provide weakrefs or dict */
1813 if (nbases > 1 &&
1814 ((may_add_dict && !add_dict) ||
1815 (may_add_weak && !add_weak))) {
1816 for (i = 0; i < nbases; i++) {
1817 tmp = PyTuple_GET_ITEM(bases, i);
1818 if (tmp == (PyObject *)base)
1819 continue; /* Skip primary base */
Guido van Rossumad47da02002-08-12 19:05:44 +00001820 assert(PyType_Check(tmp));
1821 tmptype = (PyTypeObject *)tmp;
1822 if (may_add_dict && !add_dict &&
1823 tmptype->tp_dictoffset != 0)
1824 add_dict++;
1825 if (may_add_weak && !add_weak &&
1826 tmptype->tp_weaklistoffset != 0)
1827 add_weak++;
1828 if (may_add_dict && !add_dict)
1829 continue;
1830 if (may_add_weak && !add_weak)
1831 continue;
1832 /* Nothing more to check */
1833 break;
1834 }
1835 }
Guido van Rossum9676b222001-08-17 20:32:36 +00001836 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001837
1838 /* XXX From here until type is safely allocated,
1839 "return NULL" may leak slots! */
1840
1841 /* Allocate the type object */
1842 type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
Guido van Rossumad47da02002-08-12 19:05:44 +00001843 if (type == NULL) {
1844 Py_XDECREF(slots);
Michael W. Hudsona6a277d2003-08-08 13:57:22 +00001845 Py_DECREF(bases);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001846 return NULL;
Guido van Rossumad47da02002-08-12 19:05:44 +00001847 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001848
1849 /* Keep name and slots alive in the extended type object */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001850 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001851 Py_INCREF(name);
Georg Brandlc255c7b2006-02-20 22:27:28 +00001852 et->ht_name = name;
1853 et->ht_slots = slots;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001854
Guido van Rossumdc91b992001-08-08 22:26:22 +00001855 /* Initialize tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001856 type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1857 Py_TPFLAGS_BASETYPE;
Guido van Rossum048eb752001-10-02 21:24:57 +00001858 if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1859 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossumdc91b992001-08-08 22:26:22 +00001860
Guido van Rossumdc91b992001-08-08 22:26:22 +00001861 /* Initialize essential fields */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001862 type->tp_as_number = &et->as_number;
1863 type->tp_as_sequence = &et->as_sequence;
1864 type->tp_as_mapping = &et->as_mapping;
1865 type->tp_as_buffer = &et->as_buffer;
Neal Norwitz80e7f272007-08-26 06:45:23 +00001866 type->tp_name = PyUnicode_AsString(name);
1867 if (!type->tp_name) {
1868 Py_DECREF(type);
1869 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00001870 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001871
1872 /* Set tp_base and tp_bases */
1873 type->tp_bases = bases;
1874 Py_INCREF(base);
1875 type->tp_base = base;
1876
Guido van Rossum687ae002001-10-15 22:03:32 +00001877 /* Initialize tp_dict from passed-in dict */
1878 type->tp_dict = dict = PyDict_Copy(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001879 if (dict == NULL) {
1880 Py_DECREF(type);
1881 return NULL;
1882 }
1883
Guido van Rossumc3542212001-08-16 09:18:56 +00001884 /* Set __module__ in the dict */
1885 if (PyDict_GetItemString(dict, "__module__") == NULL) {
1886 tmp = PyEval_GetGlobals();
1887 if (tmp != NULL) {
1888 tmp = PyDict_GetItemString(tmp, "__name__");
1889 if (tmp != NULL) {
1890 if (PyDict_SetItemString(dict, "__module__",
1891 tmp) < 0)
1892 return NULL;
1893 }
1894 }
1895 }
1896
Tim Peters2f93e282001-10-04 05:27:00 +00001897 /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
Tim Peters24008312002-03-17 18:56:20 +00001898 and is a string. The __doc__ accessor will first look for tp_doc;
1899 if that fails, it will still look into __dict__.
Tim Peters2f93e282001-10-04 05:27:00 +00001900 */
1901 {
1902 PyObject *doc = PyDict_GetItemString(dict, "__doc__");
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001903 if (doc != NULL && PyUnicode_Check(doc)) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00001904 size_t n;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001905 char *tp_doc;
1906 const char *str = PyUnicode_AsString(doc);
1907 if (str == NULL) {
1908 Py_DECREF(type);
1909 return NULL;
Tim Peters2f93e282001-10-04 05:27:00 +00001910 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001911 n = strlen(str);
1912 tp_doc = (char *)PyObject_MALLOC(n+1);
1913 if (tp_doc == NULL) {
1914 Py_DECREF(type);
1915 return NULL;
Neal Norwitza369c5a2007-08-25 07:41:59 +00001916 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001917 memcpy(tp_doc, str, n+1);
1918 type->tp_doc = tp_doc;
Tim Peters2f93e282001-10-04 05:27:00 +00001919 }
1920 }
1921
Tim Peters6d6c1a32001-08-02 04:15:00 +00001922 /* Special-case __new__: if it's a plain function,
1923 make it a static function */
1924 tmp = PyDict_GetItemString(dict, "__new__");
1925 if (tmp != NULL && PyFunction_Check(tmp)) {
1926 tmp = PyStaticMethod_New(tmp);
1927 if (tmp == NULL) {
1928 Py_DECREF(type);
1929 return NULL;
1930 }
1931 PyDict_SetItemString(dict, "__new__", tmp);
1932 Py_DECREF(tmp);
1933 }
1934
1935 /* Add descriptors for custom slots from __slots__, or for __dict__ */
Guido van Rossume5c691a2003-03-07 15:13:17 +00001936 mp = PyHeapType_GET_MEMBERS(et);
Neil Schemenauerc806c882001-08-29 23:54:54 +00001937 slotoffset = base->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001938 if (slots != NULL) {
1939 for (i = 0; i < nslots; i++, mp++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001940 mp->name = PyUnicode_AsString(
Tim Peters6d6c1a32001-08-02 04:15:00 +00001941 PyTuple_GET_ITEM(slots, i));
Guido van Rossum64b206c2001-12-04 17:13:22 +00001942 mp->type = T_OBJECT_EX;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001943 mp->offset = slotoffset;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001944
1945 /* __dict__ and __weakref__ are already filtered out */
1946 assert(strcmp(mp->name, "__dict__") != 0);
1947 assert(strcmp(mp->name, "__weakref__") != 0);
1948
Tim Peters6d6c1a32001-08-02 04:15:00 +00001949 slotoffset += sizeof(PyObject *);
1950 }
1951 }
Guido van Rossumad47da02002-08-12 19:05:44 +00001952 if (add_dict) {
1953 if (base->tp_itemsize)
1954 type->tp_dictoffset = -(long)sizeof(PyObject *);
1955 else
1956 type->tp_dictoffset = slotoffset;
1957 slotoffset += sizeof(PyObject *);
1958 }
1959 if (add_weak) {
1960 assert(!base->tp_itemsize);
1961 type->tp_weaklistoffset = slotoffset;
1962 slotoffset += sizeof(PyObject *);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001963 }
1964 type->tp_basicsize = slotoffset;
Guido van Rossum6fb3fde2001-08-30 20:00:07 +00001965 type->tp_itemsize = base->tp_itemsize;
Guido van Rossume5c691a2003-03-07 15:13:17 +00001966 type->tp_members = PyHeapType_GET_MEMBERS(et);
Guido van Rossum373c7412003-01-07 13:41:37 +00001967
1968 if (type->tp_weaklistoffset && type->tp_dictoffset)
1969 type->tp_getset = subtype_getsets_full;
1970 else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1971 type->tp_getset = subtype_getsets_weakref_only;
1972 else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1973 type->tp_getset = subtype_getsets_dict_only;
1974 else
1975 type->tp_getset = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001976
1977 /* Special case some slots */
1978 if (type->tp_dictoffset != 0 || nslots > 0) {
1979 if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1980 type->tp_getattro = PyObject_GenericGetAttr;
1981 if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1982 type->tp_setattro = PyObject_GenericSetAttr;
1983 }
1984 type->tp_dealloc = subtype_dealloc;
1985
Guido van Rossum9475a232001-10-05 20:51:39 +00001986 /* Enable GC unless there are really no instance variables possible */
1987 if (!(type->tp_basicsize == sizeof(PyObject) &&
1988 type->tp_itemsize == 0))
1989 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1990
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991 /* Always override allocation strategy to use regular heap */
1992 type->tp_alloc = PyType_GenericAlloc;
Guido van Rossum048eb752001-10-02 21:24:57 +00001993 if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001994 type->tp_free = PyObject_GC_Del;
Guido van Rossum9475a232001-10-05 20:51:39 +00001995 type->tp_traverse = subtype_traverse;
Guido van Rossum9923ffe2002-06-04 19:52:53 +00001996 type->tp_clear = subtype_clear;
Guido van Rossum048eb752001-10-02 21:24:57 +00001997 }
1998 else
Neil Schemenauer09a2ae52002-04-12 03:06:53 +00001999 type->tp_free = PyObject_Del;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002000
2001 /* Initialize the rest */
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002002 if (PyType_Ready(type) < 0) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00002003 Py_DECREF(type);
2004 return NULL;
2005 }
2006
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002007 /* Put the proper slots in place */
2008 fixup_slot_dispatchers(type);
Guido van Rossumf040ede2001-08-07 16:40:56 +00002009
Tim Peters6d6c1a32001-08-02 04:15:00 +00002010 return (PyObject *)type;
2011}
2012
2013/* Internal API to look for a name through the MRO.
2014 This returns a borrowed reference, and doesn't set an exception! */
2015PyObject *
2016_PyType_Lookup(PyTypeObject *type, PyObject *name)
2017{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002018 Py_ssize_t i, n;
Tim Petersa91e9642001-11-14 23:32:33 +00002019 PyObject *mro, *res, *base, *dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002020
Guido van Rossum687ae002001-10-15 22:03:32 +00002021 /* Look in tp_dict of types in MRO */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002022 mro = type->tp_mro;
Guido van Rossum23094982002-06-10 14:30:43 +00002023
2024 /* If mro is NULL, the type is either not yet initialized
2025 by PyType_Ready(), or already cleared by type_clear().
2026 Either way the safest thing to do is to return NULL. */
2027 if (mro == NULL)
2028 return NULL;
2029
Tim Peters6d6c1a32001-08-02 04:15:00 +00002030 assert(PyTuple_Check(mro));
2031 n = PyTuple_GET_SIZE(mro);
2032 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00002033 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002034 assert(PyType_Check(base));
2035 dict = ((PyTypeObject *)base)->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002036 assert(dict && PyDict_Check(dict));
2037 res = PyDict_GetItem(dict, name);
2038 if (res != NULL)
2039 return res;
2040 }
2041 return NULL;
2042}
2043
2044/* This is similar to PyObject_GenericGetAttr(),
2045 but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
2046static PyObject *
2047type_getattro(PyTypeObject *type, PyObject *name)
2048{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002049 PyTypeObject *metatype = Py_Type(type);
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002050 PyObject *meta_attribute, *attribute;
2051 descrgetfunc meta_get;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002052
2053 /* Initialize this type (we'll assume the metatype is initialized) */
2054 if (type->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00002055 if (PyType_Ready(type) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002056 return NULL;
2057 }
2058
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002059 /* No readable descriptor found yet */
2060 meta_get = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002061
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002062 /* Look for the attribute in the metatype */
2063 meta_attribute = _PyType_Lookup(metatype, name);
2064
2065 if (meta_attribute != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002066 meta_get = Py_Type(meta_attribute)->tp_descr_get;
Tim Peters34592512002-07-11 06:23:50 +00002067
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002068 if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
2069 /* Data descriptors implement tp_descr_set to intercept
2070 * writes. Assume the attribute is not overridden in
2071 * type's tp_dict (and bases): call the descriptor now.
2072 */
2073 return meta_get(meta_attribute, (PyObject *)type,
2074 (PyObject *)metatype);
2075 }
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002076 Py_INCREF(meta_attribute);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002077 }
2078
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002079 /* No data descriptor found on metatype. Look in tp_dict of this
2080 * type and its bases */
2081 attribute = _PyType_Lookup(type, name);
2082 if (attribute != NULL) {
2083 /* Implement descriptor functionality, if any */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002084 descrgetfunc local_get = Py_Type(attribute)->tp_descr_get;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002085
2086 Py_XDECREF(meta_attribute);
2087
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002088 if (local_get != NULL) {
2089 /* NULL 2nd argument indicates the descriptor was
2090 * found on the target object itself (or a base) */
2091 return local_get(attribute, (PyObject *)NULL,
2092 (PyObject *)type);
2093 }
Tim Peters34592512002-07-11 06:23:50 +00002094
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002095 Py_INCREF(attribute);
2096 return attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002097 }
2098
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002099 /* No attribute found in local __dict__ (or bases): use the
2100 * descriptor from the metatype, if any */
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00002101 if (meta_get != NULL) {
2102 PyObject *res;
2103 res = meta_get(meta_attribute, (PyObject *)type,
2104 (PyObject *)metatype);
2105 Py_DECREF(meta_attribute);
2106 return res;
2107 }
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002108
2109 /* If an ordinary attribute was found on the metatype, return it now */
2110 if (meta_attribute != NULL) {
Guido van Rossumbfc2e5e2002-04-04 17:50:54 +00002111 return meta_attribute;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002112 }
2113
2114 /* Give up */
2115 PyErr_Format(PyExc_AttributeError,
Walter Dörwald75163602007-06-11 15:47:13 +00002116 "type object '%.50s' has no attribute '%U'",
2117 type->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002118 return NULL;
2119}
2120
2121static int
2122type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2123{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002124 if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2125 PyErr_Format(
2126 PyExc_TypeError,
2127 "can't set attributes of built-in/extension type '%s'",
2128 type->tp_name);
2129 return -1;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00002130 }
Guido van Rossum8d24ee92003-03-24 23:49:49 +00002131 /* XXX Example of how I expect this to be used...
2132 if (update_subclasses(type, name, invalidate_cache, NULL) < 0)
2133 return -1;
2134 */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00002135 if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2136 return -1;
2137 return update_slot(type, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002138}
2139
2140static void
2141type_dealloc(PyTypeObject *type)
2142{
Guido van Rossume5c691a2003-03-07 15:13:17 +00002143 PyHeapTypeObject *et;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002144
2145 /* Assert this is a heap-allocated type object */
2146 assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
Guido van Rossum048eb752001-10-02 21:24:57 +00002147 _PyObject_GC_UNTRACK(type);
Guido van Rossum1c450732001-10-08 15:18:27 +00002148 PyObject_ClearWeakRefs((PyObject *)type);
Guido van Rossume5c691a2003-03-07 15:13:17 +00002149 et = (PyHeapTypeObject *)type;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002150 Py_XDECREF(type->tp_base);
2151 Py_XDECREF(type->tp_dict);
2152 Py_XDECREF(type->tp_bases);
2153 Py_XDECREF(type->tp_mro);
Guido van Rossum687ae002001-10-15 22:03:32 +00002154 Py_XDECREF(type->tp_cache);
Guido van Rossum1c450732001-10-08 15:18:27 +00002155 Py_XDECREF(type->tp_subclasses);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002156 /* A type's tp_doc is heap allocated, unlike the tp_doc slots
2157 * of most other objects. It's okay to cast it to char *.
2158 */
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002159 PyObject_Free((char *)type->tp_doc);
Georg Brandlc255c7b2006-02-20 22:27:28 +00002160 Py_XDECREF(et->ht_name);
2161 Py_XDECREF(et->ht_slots);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002162 Py_Type(type)->tp_free((PyObject *)type);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002163}
2164
Guido van Rossum1c450732001-10-08 15:18:27 +00002165static PyObject *
2166type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2167{
2168 PyObject *list, *raw, *ref;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002169 Py_ssize_t i, n;
Guido van Rossum1c450732001-10-08 15:18:27 +00002170
2171 list = PyList_New(0);
2172 if (list == NULL)
2173 return NULL;
2174 raw = type->tp_subclasses;
2175 if (raw == NULL)
2176 return list;
2177 assert(PyList_Check(raw));
2178 n = PyList_GET_SIZE(raw);
2179 for (i = 0; i < n; i++) {
2180 ref = PyList_GET_ITEM(raw, i);
Tim Peters44383382001-10-08 16:49:26 +00002181 assert(PyWeakref_CheckRef(ref));
Guido van Rossum1c450732001-10-08 15:18:27 +00002182 ref = PyWeakref_GET_OBJECT(ref);
2183 if (ref != Py_None) {
2184 if (PyList_Append(list, ref) < 0) {
2185 Py_DECREF(list);
2186 return NULL;
2187 }
2188 }
2189 }
2190 return list;
2191}
2192
Guido van Rossum47374822007-08-02 16:48:17 +00002193static PyObject *
2194type_prepare(PyObject *self, PyObject *args, PyObject *kwds)
2195{
2196 return PyDict_New();
2197}
2198
Tim Peters6d6c1a32001-08-02 04:15:00 +00002199static PyMethodDef type_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002200 {"mro", (PyCFunction)mro_external, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002201 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
Guido van Rossum1c450732001-10-08 15:18:27 +00002202 {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002203 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
Guido van Rossum47374822007-08-02 16:48:17 +00002204 {"__prepare__", (PyCFunction)type_prepare,
2205 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2206 PyDoc_STR("__prepare__() -> dict\n"
2207 "used to create the namespace for the class statement")},
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
Eric Smith8c663262007-08-25 02:26:07 +00002925
2926/*
2927 from PEP 3101, this code implements:
2928
2929 class object:
2930 def __format__(self, format_spec):
2931 return format(str(self), format_spec)
2932*/
2933static PyObject *
2934object_format(PyObject *self, PyObject *args)
2935{
2936 PyObject *format_spec;
2937 PyObject *self_as_str = NULL;
2938 PyObject *result = NULL;
2939 PyObject *format_meth = NULL;
2940
2941 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
2942 return NULL;
2943 if (!PyUnicode_Check(format_spec)) {
2944 PyErr_SetString(PyExc_TypeError, "Unicode object required");
2945 return NULL;
2946 }
2947
2948 self_as_str = PyObject_Unicode(self);
2949 if (self_as_str != NULL) {
2950 /* find the format function */
2951 format_meth = PyObject_GetAttrString(self_as_str, "__format__");
2952 if (format_meth != NULL) {
2953 /* and call it */
2954 result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL);
2955 }
2956 }
2957
2958 Py_XDECREF(self_as_str);
2959 Py_XDECREF(format_meth);
2960
2961 return result;
2962}
2963
Guido van Rossum3926a632001-09-25 16:25:58 +00002964static PyMethodDef object_methods[] = {
Guido van Rossumc53f0092003-02-18 22:05:12 +00002965 {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2966 PyDoc_STR("helper for pickle")},
Guido van Rossumd8faa362007-04-27 19:54:29 +00002967 {"__reduce__", object_reduce, METH_VARARGS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002968 PyDoc_STR("helper for pickle")},
Eric Smith8c663262007-08-25 02:26:07 +00002969 {"__format__", object_format, METH_VARARGS,
2970 PyDoc_STR("default object formatter")},
Guido van Rossum3926a632001-09-25 16:25:58 +00002971 {0}
2972};
2973
Guido van Rossum036f9992003-02-21 22:02:54 +00002974
Tim Peters6d6c1a32001-08-02 04:15:00 +00002975PyTypeObject PyBaseObject_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002976 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002977 "object", /* tp_name */
2978 sizeof(PyObject), /* tp_basicsize */
2979 0, /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002980 object_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002981 0, /* tp_print */
Guido van Rossumd8faa362007-04-27 19:54:29 +00002982 0, /* tp_getattr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002983 0, /* tp_setattr */
2984 0, /* tp_compare */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002985 object_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002986 0, /* tp_as_number */
2987 0, /* tp_as_sequence */
2988 0, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002989 (hashfunc)_Py_HashPointer, /* tp_hash */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002990 0, /* tp_call */
Guido van Rossumb8f63662001-08-15 23:57:02 +00002991 object_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002992 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum13d52f02001-08-10 21:24:08 +00002993 PyObject_GenericSetAttr, /* tp_setattro */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002994 0, /* tp_as_buffer */
2995 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Neal Norwitz5dc2a372002-08-13 22:19:13 +00002996 PyDoc_STR("The most base type"), /* tp_doc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002997 0, /* tp_traverse */
2998 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002999 object_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003000 0, /* tp_weaklistoffset */
3001 0, /* tp_iter */
3002 0, /* tp_iternext */
Guido van Rossum3926a632001-09-25 16:25:58 +00003003 object_methods, /* tp_methods */
Guido van Rossum5c294fb2001-09-25 03:43:42 +00003004 0, /* tp_members */
3005 object_getsets, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003006 0, /* tp_base */
3007 0, /* tp_dict */
3008 0, /* tp_descr_get */
3009 0, /* tp_descr_set */
3010 0, /* tp_dictoffset */
3011 object_init, /* tp_init */
3012 PyType_GenericAlloc, /* tp_alloc */
Guido van Rossum298e4212003-02-13 16:30:16 +00003013 object_new, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003014 PyObject_Del, /* tp_free */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003015};
3016
3017
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003018/* Add the methods from tp_methods to the __dict__ in a type object */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003019
3020static int
3021add_methods(PyTypeObject *type, PyMethodDef *meth)
3022{
Guido van Rossum687ae002001-10-15 22:03:32 +00003023 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003024
3025 for (; meth->ml_name != NULL; meth++) {
3026 PyObject *descr;
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00003027 if (PyDict_GetItemString(dict, meth->ml_name) &&
3028 !(meth->ml_flags & METH_COEXIST))
3029 continue;
Fred Drake7bf97152002-03-28 05:33:33 +00003030 if (meth->ml_flags & METH_CLASS) {
3031 if (meth->ml_flags & METH_STATIC) {
3032 PyErr_SetString(PyExc_ValueError,
3033 "method cannot be both class and static");
3034 return -1;
3035 }
Tim Petersbca1cbc2002-12-09 22:56:13 +00003036 descr = PyDescr_NewClassMethod(type, meth);
Fred Drake7bf97152002-03-28 05:33:33 +00003037 }
3038 else if (meth->ml_flags & METH_STATIC) {
Guido van Rossum9af48ff2003-02-11 17:12:46 +00003039 PyObject *cfunc = PyCFunction_New(meth, NULL);
3040 if (cfunc == NULL)
3041 return -1;
3042 descr = PyStaticMethod_New(cfunc);
3043 Py_DECREF(cfunc);
Fred Drake7bf97152002-03-28 05:33:33 +00003044 }
3045 else {
3046 descr = PyDescr_NewMethod(type, meth);
3047 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003048 if (descr == NULL)
3049 return -1;
Fred Drake7bf97152002-03-28 05:33:33 +00003050 if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003051 return -1;
3052 Py_DECREF(descr);
3053 }
3054 return 0;
3055}
3056
3057static int
Guido van Rossum6f799372001-09-20 20:46:19 +00003058add_members(PyTypeObject *type, PyMemberDef *memb)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003059{
Guido van Rossum687ae002001-10-15 22:03:32 +00003060 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003061
3062 for (; memb->name != NULL; memb++) {
3063 PyObject *descr;
3064 if (PyDict_GetItemString(dict, memb->name))
3065 continue;
3066 descr = PyDescr_NewMember(type, memb);
3067 if (descr == NULL)
3068 return -1;
3069 if (PyDict_SetItemString(dict, memb->name, descr) < 0)
3070 return -1;
3071 Py_DECREF(descr);
3072 }
3073 return 0;
3074}
3075
3076static int
Guido van Rossum32d34c82001-09-20 21:45:26 +00003077add_getset(PyTypeObject *type, PyGetSetDef *gsp)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003078{
Guido van Rossum687ae002001-10-15 22:03:32 +00003079 PyObject *dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003080
3081 for (; gsp->name != NULL; gsp++) {
3082 PyObject *descr;
3083 if (PyDict_GetItemString(dict, gsp->name))
3084 continue;
3085 descr = PyDescr_NewGetSet(type, gsp);
3086
3087 if (descr == NULL)
3088 return -1;
3089 if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
3090 return -1;
3091 Py_DECREF(descr);
3092 }
3093 return 0;
3094}
3095
Guido van Rossum13d52f02001-08-10 21:24:08 +00003096static void
3097inherit_special(PyTypeObject *type, PyTypeObject *base)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003098{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003099 Py_ssize_t oldsize, newsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003100
Guido van Rossum13d52f02001-08-10 21:24:08 +00003101 /* Copying basicsize is connected to the GC flags */
Neil Schemenauerc806c882001-08-29 23:54:54 +00003102 oldsize = base->tp_basicsize;
3103 newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
3104 if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3105 (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
Guido van Rossum13d52f02001-08-10 21:24:08 +00003106 (!type->tp_traverse && !type->tp_clear)) {
Neil Schemenauerc806c882001-08-29 23:54:54 +00003107 type->tp_flags |= Py_TPFLAGS_HAVE_GC;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003108 if (type->tp_traverse == NULL)
3109 type->tp_traverse = base->tp_traverse;
3110 if (type->tp_clear == NULL)
3111 type->tp_clear = base->tp_clear;
3112 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003113 {
Guido van Rossumf884b742001-12-17 17:14:22 +00003114 /* The condition below could use some explanation.
3115 It appears that tp_new is not inherited for static types
3116 whose base class is 'object'; this seems to be a precaution
3117 so that old extension types don't suddenly become
3118 callable (object.__new__ wouldn't insure the invariants
3119 that the extension type's own factory function ensures).
3120 Heap types, of course, are under our control, so they do
3121 inherit tp_new; static extension types that specify some
3122 other built-in type as the default are considered
3123 new-style-aware so they also inherit object.__new__. */
Guido van Rossum13d52f02001-08-10 21:24:08 +00003124 if (base != &PyBaseObject_Type ||
3125 (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
3126 if (type->tp_new == NULL)
3127 type->tp_new = base->tp_new;
3128 }
3129 }
Neil Schemenauerc806c882001-08-29 23:54:54 +00003130 type->tp_basicsize = newsize;
Guido van Rossum4dd64ab2001-08-14 20:04:48 +00003131
3132 /* Copy other non-function slots */
3133
3134#undef COPYVAL
3135#define COPYVAL(SLOT) \
3136 if (type->SLOT == 0) type->SLOT = base->SLOT
3137
3138 COPYVAL(tp_itemsize);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003139 COPYVAL(tp_weaklistoffset);
3140 COPYVAL(tp_dictoffset);
Thomas Wouters27d517b2007-02-25 20:39:11 +00003141
3142 /* Setup fast subclass flags */
3143 if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
3144 type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
3145 else if (PyType_IsSubtype(base, &PyType_Type))
3146 type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
3147 else if (PyType_IsSubtype(base, &PyLong_Type))
3148 type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
3149 else if (PyType_IsSubtype(base, &PyString_Type))
3150 type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
3151 else if (PyType_IsSubtype(base, &PyUnicode_Type))
3152 type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
3153 else if (PyType_IsSubtype(base, &PyTuple_Type))
3154 type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
3155 else if (PyType_IsSubtype(base, &PyList_Type))
3156 type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
3157 else if (PyType_IsSubtype(base, &PyDict_Type))
3158 type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003159}
3160
Guido van Rossum38938152006-08-21 23:36:26 +00003161/* Map rich comparison operators to their __xx__ namesakes */
3162static char *name_op[] = {
3163 "__lt__",
3164 "__le__",
3165 "__eq__",
3166 "__ne__",
3167 "__gt__",
3168 "__ge__",
3169 /* These are only for overrides_cmp_or_hash(): */
3170 "__cmp__",
3171 "__hash__",
3172};
3173
3174static int
3175overrides_cmp_or_hash(PyTypeObject *type)
3176{
3177 int i;
3178 PyObject *dict = type->tp_dict;
3179
3180 assert(dict != NULL);
3181 for (i = 0; i < 8; i++) {
3182 if (PyDict_GetItemString(dict, name_op[i]) != NULL)
3183 return 1;
3184 }
3185 return 0;
3186}
3187
Guido van Rossum13d52f02001-08-10 21:24:08 +00003188static void
3189inherit_slots(PyTypeObject *type, PyTypeObject *base)
3190{
3191 PyTypeObject *basebase;
3192
3193#undef SLOTDEFINED
Tim Peters6d6c1a32001-08-02 04:15:00 +00003194#undef COPYSLOT
3195#undef COPYNUM
3196#undef COPYSEQ
3197#undef COPYMAP
Guido van Rossum5af588b2001-10-12 14:13:21 +00003198#undef COPYBUF
Guido van Rossum13d52f02001-08-10 21:24:08 +00003199
3200#define SLOTDEFINED(SLOT) \
3201 (base->SLOT != 0 && \
3202 (basebase == NULL || base->SLOT != basebase->SLOT))
3203
Tim Peters6d6c1a32001-08-02 04:15:00 +00003204#define COPYSLOT(SLOT) \
Guido van Rossum13d52f02001-08-10 21:24:08 +00003205 if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
Tim Peters6d6c1a32001-08-02 04:15:00 +00003206
3207#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
3208#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
3209#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003210#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003211
Guido van Rossum13d52f02001-08-10 21:24:08 +00003212 /* This won't inherit indirect slots (from tp_as_number etc.)
3213 if type doesn't provide the space. */
3214
3215 if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
3216 basebase = base->tp_base;
3217 if (basebase->tp_as_number == NULL)
3218 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003219 COPYNUM(nb_add);
3220 COPYNUM(nb_subtract);
3221 COPYNUM(nb_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003222 COPYNUM(nb_remainder);
3223 COPYNUM(nb_divmod);
3224 COPYNUM(nb_power);
3225 COPYNUM(nb_negative);
3226 COPYNUM(nb_positive);
3227 COPYNUM(nb_absolute);
Jack Diederich4dafcc42006-11-28 19:15:13 +00003228 COPYNUM(nb_bool);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003229 COPYNUM(nb_invert);
3230 COPYNUM(nb_lshift);
3231 COPYNUM(nb_rshift);
3232 COPYNUM(nb_and);
3233 COPYNUM(nb_xor);
3234 COPYNUM(nb_or);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003235 COPYNUM(nb_int);
3236 COPYNUM(nb_long);
3237 COPYNUM(nb_float);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003238 COPYNUM(nb_inplace_add);
3239 COPYNUM(nb_inplace_subtract);
3240 COPYNUM(nb_inplace_multiply);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003241 COPYNUM(nb_inplace_remainder);
3242 COPYNUM(nb_inplace_power);
3243 COPYNUM(nb_inplace_lshift);
3244 COPYNUM(nb_inplace_rshift);
3245 COPYNUM(nb_inplace_and);
3246 COPYNUM(nb_inplace_xor);
3247 COPYNUM(nb_inplace_or);
Neal Norwitzbcc0db82006-03-24 08:14:36 +00003248 COPYNUM(nb_true_divide);
3249 COPYNUM(nb_floor_divide);
3250 COPYNUM(nb_inplace_true_divide);
3251 COPYNUM(nb_inplace_floor_divide);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003252 COPYNUM(nb_index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003253 }
3254
Guido van Rossum13d52f02001-08-10 21:24:08 +00003255 if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
3256 basebase = base->tp_base;
3257 if (basebase->tp_as_sequence == NULL)
3258 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003259 COPYSEQ(sq_length);
3260 COPYSEQ(sq_concat);
3261 COPYSEQ(sq_repeat);
3262 COPYSEQ(sq_item);
3263 COPYSEQ(sq_slice);
3264 COPYSEQ(sq_ass_item);
3265 COPYSEQ(sq_ass_slice);
3266 COPYSEQ(sq_contains);
3267 COPYSEQ(sq_inplace_concat);
3268 COPYSEQ(sq_inplace_repeat);
3269 }
3270
Guido van Rossum13d52f02001-08-10 21:24:08 +00003271 if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
3272 basebase = base->tp_base;
3273 if (basebase->tp_as_mapping == NULL)
3274 basebase = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003275 COPYMAP(mp_length);
3276 COPYMAP(mp_subscript);
3277 COPYMAP(mp_ass_subscript);
3278 }
3279
Tim Petersfc57ccb2001-10-12 02:38:24 +00003280 if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
3281 basebase = base->tp_base;
3282 if (basebase->tp_as_buffer == NULL)
3283 basebase = NULL;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00003284 COPYBUF(bf_getbuffer);
3285 COPYBUF(bf_releasebuffer);
Tim Petersfc57ccb2001-10-12 02:38:24 +00003286 }
3287
Guido van Rossum13d52f02001-08-10 21:24:08 +00003288 basebase = base->tp_base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003289
Tim Peters6d6c1a32001-08-02 04:15:00 +00003290 COPYSLOT(tp_dealloc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003291 if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
3292 type->tp_getattr = base->tp_getattr;
3293 type->tp_getattro = base->tp_getattro;
3294 }
3295 if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3296 type->tp_setattr = base->tp_setattr;
3297 type->tp_setattro = base->tp_setattro;
3298 }
3299 /* tp_compare see tp_richcompare */
3300 COPYSLOT(tp_repr);
Guido van Rossumb8f63662001-08-15 23:57:02 +00003301 /* tp_hash see tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003302 COPYSLOT(tp_call);
3303 COPYSLOT(tp_str);
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003304 {
Guido van Rossum38938152006-08-21 23:36:26 +00003305 /* Copy comparison-related slots only when
3306 not overriding them anywhere */
Guido van Rossumb8f63662001-08-15 23:57:02 +00003307 if (type->tp_compare == NULL &&
3308 type->tp_richcompare == NULL &&
Guido van Rossum38938152006-08-21 23:36:26 +00003309 type->tp_hash == NULL &&
3310 !overrides_cmp_or_hash(type))
Guido van Rossumb8f63662001-08-15 23:57:02 +00003311 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003312 type->tp_compare = base->tp_compare;
3313 type->tp_richcompare = base->tp_richcompare;
Guido van Rossumb8f63662001-08-15 23:57:02 +00003314 type->tp_hash = base->tp_hash;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003315 }
3316 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003317 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003318 COPYSLOT(tp_iter);
3319 COPYSLOT(tp_iternext);
3320 }
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003321 {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003322 COPYSLOT(tp_descr_get);
3323 COPYSLOT(tp_descr_set);
3324 COPYSLOT(tp_dictoffset);
3325 COPYSLOT(tp_init);
3326 COPYSLOT(tp_alloc);
Guido van Rossumcc8fe042002-04-05 17:10:16 +00003327 COPYSLOT(tp_is_gc);
Tim Peters3cfe7542003-05-21 21:29:48 +00003328 if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
3329 (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
3330 /* They agree about gc. */
3331 COPYSLOT(tp_free);
3332 }
3333 else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
3334 type->tp_free == NULL &&
Neal Norwitz30d1c512007-08-19 22:48:23 +00003335 base->tp_free == PyObject_Free) {
Tim Peters3cfe7542003-05-21 21:29:48 +00003336 /* A bit of magic to plug in the correct default
3337 * tp_free function when a derived class adds gc,
3338 * didn't define tp_free, and the base uses the
3339 * default non-gc tp_free.
3340 */
3341 type->tp_free = PyObject_GC_Del;
3342 }
3343 /* else they didn't agree about gc, and there isn't something
3344 * obvious to be done -- the type is on its own.
3345 */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003347}
3348
Jeremy Hylton938ace62002-07-17 16:30:39 +00003349static int add_operators(PyTypeObject *);
Guido van Rossum13d52f02001-08-10 21:24:08 +00003350
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351int
Guido van Rossum528b7eb2001-08-07 17:24:28 +00003352PyType_Ready(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003353{
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003354 PyObject *dict, *bases;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003355 PyTypeObject *base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003356 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357
Guido van Rossumcab05802002-06-10 15:29:03 +00003358 if (type->tp_flags & Py_TPFLAGS_READY) {
3359 assert(type->tp_dict != NULL);
Guido van Rossumd614f972001-08-10 17:39:49 +00003360 return 0;
Guido van Rossumcab05802002-06-10 15:29:03 +00003361 }
Guido van Rossumd614f972001-08-10 17:39:49 +00003362 assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
Guido van Rossumd614f972001-08-10 17:39:49 +00003363
3364 type->tp_flags |= Py_TPFLAGS_READYING;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003365
Tim Peters36eb4df2003-03-23 03:33:13 +00003366#ifdef Py_TRACE_REFS
3367 /* PyType_Ready is the closest thing we have to a choke point
3368 * for type objects, so is the best place I can think of to try
3369 * to get type objects into the doubly-linked list of all objects.
3370 * Still, not all type objects go thru PyType_Ready.
3371 */
Tim Peters7571a0f2003-03-23 17:52:28 +00003372 _Py_AddToAllObjects((PyObject *)type, 0);
Tim Peters36eb4df2003-03-23 03:33:13 +00003373#endif
3374
Tim Peters6d6c1a32001-08-02 04:15:00 +00003375 /* Initialize tp_base (defaults to BaseObject unless that's us) */
3376 base = type->tp_base;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003377 if (base == NULL && type != &PyBaseObject_Type) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00003378 base = type->tp_base = &PyBaseObject_Type;
Martin v. Löwisbf608752004-08-18 13:16:54 +00003379 Py_INCREF(base);
3380 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003381
Guido van Rossumd8faa362007-04-27 19:54:29 +00003382 /* Now the only way base can still be NULL is if type is
3383 * &PyBaseObject_Type.
3384 */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003385
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003386 /* Initialize the base class */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00003387 if (base != NULL && base->tp_dict == NULL) {
Guido van Rossum323a9cf2002-08-14 17:26:30 +00003388 if (PyType_Ready(base) < 0)
3389 goto error;
3390 }
3391
Guido van Rossumd8faa362007-04-27 19:54:29 +00003392 /* Initialize ob_type if NULL. This means extensions that want to be
Guido van Rossum0986d822002-04-08 01:38:42 +00003393 compilable separately on Windows can call PyType_Ready() instead of
3394 initializing the ob_type field of their type objects. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003395 /* The test for base != NULL is really unnecessary, since base is only
3396 NULL when type is &PyBaseObject_Type, and we know its ob_type is
3397 not NULL (it's initialized to &PyType_Type). But coverity doesn't
3398 know that. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003399 if (Py_Type(type) == NULL && base != NULL)
3400 Py_Type(type) = Py_Type(base);
Guido van Rossum0986d822002-04-08 01:38:42 +00003401
Tim Peters6d6c1a32001-08-02 04:15:00 +00003402 /* Initialize tp_bases */
3403 bases = type->tp_bases;
3404 if (bases == NULL) {
3405 if (base == NULL)
3406 bases = PyTuple_New(0);
3407 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003408 bases = PyTuple_Pack(1, base);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003409 if (bases == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003410 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003411 type->tp_bases = bases;
3412 }
3413
Guido van Rossum687ae002001-10-15 22:03:32 +00003414 /* Initialize tp_dict */
3415 dict = type->tp_dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003416 if (dict == NULL) {
3417 dict = PyDict_New();
3418 if (dict == NULL)
Guido van Rossumd614f972001-08-10 17:39:49 +00003419 goto error;
Guido van Rossum687ae002001-10-15 22:03:32 +00003420 type->tp_dict = dict;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003421 }
3422
Guido van Rossum687ae002001-10-15 22:03:32 +00003423 /* Add type-specific descriptors to tp_dict */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003424 if (add_operators(type) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003425 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003426 if (type->tp_methods != NULL) {
3427 if (add_methods(type, type->tp_methods) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003428 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003429 }
3430 if (type->tp_members != NULL) {
3431 if (add_members(type, type->tp_members) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003432 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003433 }
3434 if (type->tp_getset != NULL) {
3435 if (add_getset(type, type->tp_getset) < 0)
Guido van Rossumd614f972001-08-10 17:39:49 +00003436 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003437 }
3438
Tim Peters6d6c1a32001-08-02 04:15:00 +00003439 /* Calculate method resolution order */
3440 if (mro_internal(type) < 0) {
Guido van Rossumd614f972001-08-10 17:39:49 +00003441 goto error;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003442 }
3443
Guido van Rossum13d52f02001-08-10 21:24:08 +00003444 /* Inherit special flags from dominant base */
3445 if (type->tp_base != NULL)
3446 inherit_special(type, type->tp_base);
3447
Tim Peters6d6c1a32001-08-02 04:15:00 +00003448 /* Initialize tp_dict properly */
Guido van Rossum2f3ca6e2001-10-15 21:05:10 +00003449 bases = type->tp_mro;
3450 assert(bases != NULL);
3451 assert(PyTuple_Check(bases));
3452 n = PyTuple_GET_SIZE(bases);
3453 for (i = 1; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003454 PyObject *b = PyTuple_GET_ITEM(bases, i);
3455 if (PyType_Check(b))
3456 inherit_slots(type, (PyTypeObject *)b);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003457 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003458
Tim Peters3cfe7542003-05-21 21:29:48 +00003459 /* Sanity check for tp_free. */
3460 if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
3461 (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003462 /* This base class needs to call tp_free, but doesn't have
3463 * one, or its tp_free is for non-gc'ed objects.
3464 */
Tim Peters3cfe7542003-05-21 21:29:48 +00003465 PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
3466 "gc and is a base type but has inappropriate "
3467 "tp_free slot",
3468 type->tp_name);
3469 goto error;
3470 }
3471
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003472 /* if the type dictionary doesn't contain a __doc__, set it from
3473 the tp_doc slot.
3474 */
3475 if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3476 if (type->tp_doc != NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +00003477 PyObject *doc = PyUnicode_FromString(type->tp_doc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003478 if (doc == NULL)
3479 goto error;
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003480 PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3481 Py_DECREF(doc);
3482 } else {
Guido van Rossumd4641072002-04-03 02:13:37 +00003483 PyDict_SetItemString(type->tp_dict,
3484 "__doc__", Py_None);
Martin v. Löwisf9bd6b02002-02-18 17:46:48 +00003485 }
3486 }
3487
Guido van Rossum38938152006-08-21 23:36:26 +00003488 /* Hack for tp_hash and __hash__.
3489 If after all that, tp_hash is still NULL, and __hash__ is not in
3490 tp_dict, set tp_dict['__hash__'] equal to None.
3491 This signals that __hash__ is not inherited.
3492 */
3493 if (type->tp_hash == NULL) {
3494 if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) {
3495 if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0)
3496 goto error;
3497 }
3498 }
3499
Guido van Rossum13d52f02001-08-10 21:24:08 +00003500 /* Some more special stuff */
3501 base = type->tp_base;
3502 if (base != NULL) {
3503 if (type->tp_as_number == NULL)
3504 type->tp_as_number = base->tp_as_number;
3505 if (type->tp_as_sequence == NULL)
3506 type->tp_as_sequence = base->tp_as_sequence;
3507 if (type->tp_as_mapping == NULL)
3508 type->tp_as_mapping = base->tp_as_mapping;
Guido van Rossumeea47182003-02-11 20:39:59 +00003509 if (type->tp_as_buffer == NULL)
3510 type->tp_as_buffer = base->tp_as_buffer;
Guido van Rossum13d52f02001-08-10 21:24:08 +00003511 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003512
Guido van Rossum1c450732001-10-08 15:18:27 +00003513 /* Link into each base class's list of subclasses */
3514 bases = type->tp_bases;
3515 n = PyTuple_GET_SIZE(bases);
3516 for (i = 0; i < n; i++) {
Tim Petersa91e9642001-11-14 23:32:33 +00003517 PyObject *b = PyTuple_GET_ITEM(bases, i);
3518 if (PyType_Check(b) &&
3519 add_subclass((PyTypeObject *)b, type) < 0)
Guido van Rossum1c450732001-10-08 15:18:27 +00003520 goto error;
3521 }
3522
Guido van Rossum13d52f02001-08-10 21:24:08 +00003523 /* All done -- set the ready flag */
Guido van Rossumd614f972001-08-10 17:39:49 +00003524 assert(type->tp_dict != NULL);
3525 type->tp_flags =
3526 (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003527 return 0;
Guido van Rossumd614f972001-08-10 17:39:49 +00003528
3529 error:
3530 type->tp_flags &= ~Py_TPFLAGS_READYING;
3531 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003532}
3533
Guido van Rossum1c450732001-10-08 15:18:27 +00003534static int
3535add_subclass(PyTypeObject *base, PyTypeObject *type)
3536{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003537 Py_ssize_t i;
3538 int result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003539 PyObject *list, *ref, *newobj;
Guido van Rossum1c450732001-10-08 15:18:27 +00003540
3541 list = base->tp_subclasses;
3542 if (list == NULL) {
3543 base->tp_subclasses = list = PyList_New(0);
3544 if (list == NULL)
3545 return -1;
3546 }
3547 assert(PyList_Check(list));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003548 newobj = PyWeakref_NewRef((PyObject *)type, NULL);
Guido van Rossum1c450732001-10-08 15:18:27 +00003549 i = PyList_GET_SIZE(list);
3550 while (--i >= 0) {
3551 ref = PyList_GET_ITEM(list, i);
3552 assert(PyWeakref_CheckRef(ref));
Guido van Rossum3930bc32002-10-18 13:51:49 +00003553 if (PyWeakref_GET_OBJECT(ref) == Py_None)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003554 return PyList_SetItem(list, i, newobj);
Guido van Rossum1c450732001-10-08 15:18:27 +00003555 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003556 result = PyList_Append(list, newobj);
3557 Py_DECREF(newobj);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003558 return result;
Guido van Rossum1c450732001-10-08 15:18:27 +00003559}
3560
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003561static void
3562remove_subclass(PyTypeObject *base, PyTypeObject *type)
3563{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003564 Py_ssize_t i;
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003565 PyObject *list, *ref;
3566
3567 list = base->tp_subclasses;
3568 if (list == NULL) {
3569 return;
3570 }
3571 assert(PyList_Check(list));
3572 i = PyList_GET_SIZE(list);
3573 while (--i >= 0) {
3574 ref = PyList_GET_ITEM(list, i);
3575 assert(PyWeakref_CheckRef(ref));
3576 if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3577 /* this can't fail, right? */
3578 PySequence_DelItem(list, i);
3579 return;
3580 }
3581 }
3582}
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003584static int
3585check_num_args(PyObject *ob, int n)
3586{
3587 if (!PyTuple_CheckExact(ob)) {
3588 PyErr_SetString(PyExc_SystemError,
3589 "PyArg_UnpackTuple() argument list is not a tuple");
3590 return 0;
3591 }
3592 if (n == PyTuple_GET_SIZE(ob))
3593 return 1;
3594 PyErr_Format(
3595 PyExc_TypeError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00003596 "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003597 return 0;
3598}
3599
Tim Peters6d6c1a32001-08-02 04:15:00 +00003600/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3601
3602/* There's a wrapper *function* for each distinct function typedef used
Guido van Rossumd8faa362007-04-27 19:54:29 +00003603 for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
Tim Peters6d6c1a32001-08-02 04:15:00 +00003604 wrapper *table* for each distinct operation (e.g. __len__, __add__).
3605 Most tables have only one entry; the tables for binary operators have two
3606 entries, one regular and one with reversed arguments. */
3607
3608static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003609wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003610{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003611 lenfunc func = (lenfunc)wrapped;
3612 Py_ssize_t res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003614 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003615 return NULL;
3616 res = (*func)(self);
3617 if (res == -1 && PyErr_Occurred())
3618 return NULL;
3619 return PyInt_FromLong((long)res);
3620}
3621
Tim Peters6d6c1a32001-08-02 04:15:00 +00003622static PyObject *
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003623wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
3624{
3625 inquiry func = (inquiry)wrapped;
3626 int res;
3627
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003628 if (!check_num_args(args, 0))
Raymond Hettingerf34f2642003-10-11 17:29:04 +00003629 return NULL;
3630 res = (*func)(self);
3631 if (res == -1 && PyErr_Occurred())
3632 return NULL;
3633 return PyBool_FromLong((long)res);
3634}
3635
3636static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3638{
3639 binaryfunc func = (binaryfunc)wrapped;
3640 PyObject *other;
3641
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003642 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003643 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003644 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003645 return (*func)(self, other);
3646}
3647
3648static PyObject *
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003649wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3650{
3651 binaryfunc func = (binaryfunc)wrapped;
3652 PyObject *other;
3653
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003654 if (!check_num_args(args, 1))
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003655 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003656 other = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003657 return (*func)(self, other);
3658}
3659
3660static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003661wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3662{
3663 binaryfunc func = (binaryfunc)wrapped;
3664 PyObject *other;
3665
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003666 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003667 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003668 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003669 if (!PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossum0eb2a6e2001-10-09 11:07:24 +00003670 Py_INCREF(Py_NotImplemented);
3671 return Py_NotImplemented;
3672 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003673 return (*func)(other, self);
3674}
3675
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00003676static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003677wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3678{
3679 ternaryfunc func = (ternaryfunc)wrapped;
3680 PyObject *other;
3681 PyObject *third = Py_None;
3682
3683 /* Note: This wrapper only works for __pow__() */
3684
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003685 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003686 return NULL;
3687 return (*func)(self, other, third);
3688}
3689
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003690static PyObject *
3691wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3692{
3693 ternaryfunc func = (ternaryfunc)wrapped;
3694 PyObject *other;
3695 PyObject *third = Py_None;
3696
3697 /* Note: This wrapper only works for __pow__() */
3698
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003699 if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
Guido van Rossum9bea3ab2001-09-28 22:58:52 +00003700 return NULL;
3701 return (*func)(other, self, third);
3702}
3703
Tim Peters6d6c1a32001-08-02 04:15:00 +00003704static PyObject *
3705wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3706{
3707 unaryfunc func = (unaryfunc)wrapped;
3708
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003709 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003710 return NULL;
3711 return (*func)(self);
3712}
3713
Tim Peters6d6c1a32001-08-02 04:15:00 +00003714static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003715wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003716{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003717 ssizeargfunc func = (ssizeargfunc)wrapped;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003718 PyObject* o;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003719 Py_ssize_t i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003720
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003721 if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
3722 return NULL;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003723 i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003724 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003725 return NULL;
3726 return (*func)(self, i);
3727}
3728
Martin v. Löwis18e16552006-02-15 17:27:45 +00003729static Py_ssize_t
Guido van Rossum5d815f32001-08-17 21:57:47 +00003730getindex(PyObject *self, PyObject *arg)
3731{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003732 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003733
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003734 i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003735 if (i == -1 && PyErr_Occurred())
3736 return -1;
3737 if (i < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003738 PySequenceMethods *sq = Py_Type(self)->tp_as_sequence;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003739 if (sq && sq->sq_length) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003740 Py_ssize_t n = (*sq->sq_length)(self);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003741 if (n < 0)
3742 return -1;
3743 i += n;
3744 }
3745 }
3746 return i;
3747}
3748
3749static PyObject *
3750wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3751{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003752 ssizeargfunc func = (ssizeargfunc)wrapped;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003753 PyObject *arg;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003754 Py_ssize_t i;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003755
Guido van Rossumf4593e02001-10-03 12:09:30 +00003756 if (PyTuple_GET_SIZE(args) == 1) {
3757 arg = PyTuple_GET_ITEM(args, 0);
3758 i = getindex(self, arg);
3759 if (i == -1 && PyErr_Occurred())
3760 return NULL;
3761 return (*func)(self, i);
3762 }
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003763 check_num_args(args, 1);
Guido van Rossumf4593e02001-10-03 12:09:30 +00003764 assert(PyErr_Occurred());
3765 return NULL;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003766}
3767
Tim Peters6d6c1a32001-08-02 04:15:00 +00003768static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003769wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003770{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003771 ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
3772 Py_ssize_t i, j;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003773
Martin v. Löwis18e16552006-02-15 17:27:45 +00003774 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003775 return NULL;
3776 return (*func)(self, i, j);
3777}
3778
Tim Peters6d6c1a32001-08-02 04:15:00 +00003779static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003780wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003781{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003782 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3783 Py_ssize_t i;
3784 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003785 PyObject *arg, *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003786
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003787 if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003788 return NULL;
3789 i = getindex(self, arg);
3790 if (i == -1 && PyErr_Occurred())
Tim Peters6d6c1a32001-08-02 04:15:00 +00003791 return NULL;
3792 res = (*func)(self, i, value);
3793 if (res == -1 && PyErr_Occurred())
3794 return NULL;
3795 Py_INCREF(Py_None);
3796 return Py_None;
3797}
3798
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003799static PyObject *
Guido van Rossum5d815f32001-08-17 21:57:47 +00003800wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003801{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003802 ssizeobjargproc func = (ssizeobjargproc)wrapped;
3803 Py_ssize_t i;
3804 int res;
Guido van Rossum5d815f32001-08-17 21:57:47 +00003805 PyObject *arg;
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003806
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003807 if (!check_num_args(args, 1))
Guido van Rossum5d815f32001-08-17 21:57:47 +00003808 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003809 arg = PyTuple_GET_ITEM(args, 0);
Guido van Rossum5d815f32001-08-17 21:57:47 +00003810 i = getindex(self, arg);
3811 if (i == -1 && PyErr_Occurred())
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003812 return NULL;
3813 res = (*func)(self, i, NULL);
3814 if (res == -1 && PyErr_Occurred())
3815 return NULL;
3816 Py_INCREF(Py_None);
3817 return Py_None;
3818}
3819
Tim Peters6d6c1a32001-08-02 04:15:00 +00003820static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00003821wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003822{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003823 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3824 Py_ssize_t i, j;
3825 int res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003826 PyObject *value;
3827
Martin v. Löwis18e16552006-02-15 17:27:45 +00003828 if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003829 return NULL;
3830 res = (*func)(self, i, j, value);
3831 if (res == -1 && PyErr_Occurred())
3832 return NULL;
3833 Py_INCREF(Py_None);
3834 return Py_None;
3835}
3836
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003837static PyObject *
3838wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3839{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003840 ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
3841 Py_ssize_t i, j;
3842 int res;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003843
Martin v. Löwis18e16552006-02-15 17:27:45 +00003844 if (!PyArg_ParseTuple(args, "nn", &i, &j))
Guido van Rossum7b9144b2001-10-09 19:39:46 +00003845 return NULL;
3846 res = (*func)(self, i, j, NULL);
3847 if (res == -1 && PyErr_Occurred())
3848 return NULL;
3849 Py_INCREF(Py_None);
3850 return Py_None;
3851}
3852
Tim Peters6d6c1a32001-08-02 04:15:00 +00003853/* XXX objobjproc is a misnomer; should be objargpred */
3854static PyObject *
3855wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3856{
3857 objobjproc func = (objobjproc)wrapped;
3858 int res;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003859 PyObject *value;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003861 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003862 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003863 value = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003864 res = (*func)(self, value);
3865 if (res == -1 && PyErr_Occurred())
3866 return NULL;
Guido van Rossum22c3dda2003-10-09 03:46:35 +00003867 else
3868 return PyBool_FromLong(res);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869}
3870
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871static PyObject *
3872wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3873{
3874 objobjargproc func = (objobjargproc)wrapped;
3875 int res;
3876 PyObject *key, *value;
3877
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003878 if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003879 return NULL;
3880 res = (*func)(self, key, value);
3881 if (res == -1 && PyErr_Occurred())
3882 return NULL;
3883 Py_INCREF(Py_None);
3884 return Py_None;
3885}
3886
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003887static PyObject *
3888wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3889{
3890 objobjargproc func = (objobjargproc)wrapped;
3891 int res;
3892 PyObject *key;
3893
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003894 if (!check_num_args(args, 1))
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003895 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003896 key = PyTuple_GET_ITEM(args, 0);
Guido van Rossum2b8d7bd2001-08-02 15:31:58 +00003897 res = (*func)(self, key, NULL);
3898 if (res == -1 && PyErr_Occurred())
3899 return NULL;
3900 Py_INCREF(Py_None);
3901 return Py_None;
3902}
3903
Tim Peters6d6c1a32001-08-02 04:15:00 +00003904static PyObject *
3905wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3906{
3907 cmpfunc func = (cmpfunc)wrapped;
3908 int res;
3909 PyObject *other;
3910
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003911 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003912 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003913 other = PyTuple_GET_ITEM(args, 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003914 if (Py_Type(other)->tp_compare != func &&
3915 !PyType_IsSubtype(Py_Type(other), Py_Type(self))) {
Guido van Rossumceccae52001-09-18 20:03:57 +00003916 PyErr_Format(
3917 PyExc_TypeError,
3918 "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003919 Py_Type(self)->tp_name,
3920 Py_Type(self)->tp_name,
3921 Py_Type(other)->tp_name);
Guido van Rossumceccae52001-09-18 20:03:57 +00003922 return NULL;
3923 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003924 res = (*func)(self, other);
3925 if (PyErr_Occurred())
3926 return NULL;
3927 return PyInt_FromLong((long)res);
3928}
3929
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003930/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
Guido van Rossum52b27052003-04-15 20:05:10 +00003931 This is called the Carlo Verre hack after its discoverer. */
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003932static int
3933hackcheck(PyObject *self, setattrofunc func, char *what)
3934{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003935 PyTypeObject *type = Py_Type(self);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003936 while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
3937 type = type->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003938 /* If type is NULL now, this is a really weird type.
3939 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00003940 if (type && type->tp_setattro != func) {
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003941 PyErr_Format(PyExc_TypeError,
3942 "can't apply this %s to %s object",
3943 what,
3944 type->tp_name);
3945 return 0;
3946 }
3947 return 1;
3948}
3949
Tim Peters6d6c1a32001-08-02 04:15:00 +00003950static PyObject *
3951wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3952{
3953 setattrofunc func = (setattrofunc)wrapped;
3954 int res;
3955 PyObject *name, *value;
3956
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00003957 if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003958 return NULL;
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003959 if (!hackcheck(self, func, "__setattr__"))
3960 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003961 res = (*func)(self, name, value);
3962 if (res < 0)
3963 return NULL;
3964 Py_INCREF(Py_None);
3965 return Py_None;
3966}
3967
3968static PyObject *
3969wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3970{
3971 setattrofunc func = (setattrofunc)wrapped;
3972 int res;
3973 PyObject *name;
3974
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003975 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003977 name = PyTuple_GET_ITEM(args, 0);
Guido van Rossum4dcdb782003-04-14 21:46:03 +00003978 if (!hackcheck(self, func, "__delattr__"))
3979 return NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00003980 res = (*func)(self, name, NULL);
3981 if (res < 0)
3982 return NULL;
3983 Py_INCREF(Py_None);
3984 return Py_None;
3985}
3986
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987static PyObject *
3988wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3989{
3990 hashfunc func = (hashfunc)wrapped;
3991 long res;
3992
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00003993 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00003994 return NULL;
3995 res = (*func)(self);
3996 if (res == -1 && PyErr_Occurred())
3997 return NULL;
3998 return PyInt_FromLong(res);
3999}
4000
Tim Peters6d6c1a32001-08-02 04:15:00 +00004001static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004002wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004003{
4004 ternaryfunc func = (ternaryfunc)wrapped;
4005
Guido van Rossumc8e56452001-10-22 00:43:43 +00004006 return (*func)(self, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004007}
4008
Tim Peters6d6c1a32001-08-02 04:15:00 +00004009static PyObject *
4010wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
4011{
4012 richcmpfunc func = (richcmpfunc)wrapped;
4013 PyObject *other;
4014
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004015 if (!check_num_args(args, 1))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004016 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004017 other = PyTuple_GET_ITEM(args, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018 return (*func)(self, other, op);
4019}
4020
4021#undef RICHCMP_WRAPPER
4022#define RICHCMP_WRAPPER(NAME, OP) \
4023static PyObject * \
4024richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
4025{ \
4026 return wrap_richcmpfunc(self, args, wrapped, OP); \
4027}
4028
Jack Jansen8e938b42001-08-08 15:29:49 +00004029RICHCMP_WRAPPER(lt, Py_LT)
4030RICHCMP_WRAPPER(le, Py_LE)
4031RICHCMP_WRAPPER(eq, Py_EQ)
4032RICHCMP_WRAPPER(ne, Py_NE)
4033RICHCMP_WRAPPER(gt, Py_GT)
4034RICHCMP_WRAPPER(ge, Py_GE)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004035
Tim Peters6d6c1a32001-08-02 04:15:00 +00004036static PyObject *
4037wrap_next(PyObject *self, PyObject *args, void *wrapped)
4038{
4039 unaryfunc func = (unaryfunc)wrapped;
4040 PyObject *res;
4041
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004042 if (!check_num_args(args, 0))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004043 return NULL;
4044 res = (*func)(self);
4045 if (res == NULL && !PyErr_Occurred())
4046 PyErr_SetNone(PyExc_StopIteration);
4047 return res;
4048}
4049
Tim Peters6d6c1a32001-08-02 04:15:00 +00004050static PyObject *
4051wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
4052{
4053 descrgetfunc func = (descrgetfunc)wrapped;
4054 PyObject *obj;
4055 PyObject *type = NULL;
4056
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004057 if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004058 return NULL;
Guido van Rossum82ed25c2003-02-11 16:25:43 +00004059 if (obj == Py_None)
4060 obj = NULL;
4061 if (type == Py_None)
4062 type = NULL;
4063 if (type == NULL &&obj == NULL) {
4064 PyErr_SetString(PyExc_TypeError,
4065 "__get__(None, None) is invalid");
4066 return NULL;
4067 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004068 return (*func)(self, obj, type);
4069}
4070
Tim Peters6d6c1a32001-08-02 04:15:00 +00004071static PyObject *
Guido van Rossum7b9144b2001-10-09 19:39:46 +00004072wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073{
4074 descrsetfunc func = (descrsetfunc)wrapped;
4075 PyObject *obj, *value;
4076 int ret;
4077
Raymond Hettinger56bb16f2003-10-11 19:32:18 +00004078 if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079 return NULL;
4080 ret = (*func)(self, obj, value);
4081 if (ret < 0)
4082 return NULL;
4083 Py_INCREF(Py_None);
4084 return Py_None;
4085}
Guido van Rossum22b13872002-08-06 21:41:44 +00004086
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004087static PyObject *
4088wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
4089{
4090 descrsetfunc func = (descrsetfunc)wrapped;
4091 PyObject *obj;
4092 int ret;
4093
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004094 if (!check_num_args(args, 1))
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004095 return NULL;
Raymond Hettinger6a8bbdb2003-12-13 15:21:55 +00004096 obj = PyTuple_GET_ITEM(args, 0);
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00004097 ret = (*func)(self, obj, NULL);
4098 if (ret < 0)
4099 return NULL;
4100 Py_INCREF(Py_None);
4101 return Py_None;
4102}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004103
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104static PyObject *
Guido van Rossumc8e56452001-10-22 00:43:43 +00004105wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004106{
4107 initproc func = (initproc)wrapped;
4108
Guido van Rossumc8e56452001-10-22 00:43:43 +00004109 if (func(self, args, kwds) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004110 return NULL;
4111 Py_INCREF(Py_None);
4112 return Py_None;
4113}
4114
Tim Peters6d6c1a32001-08-02 04:15:00 +00004115static PyObject *
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004116tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117{
Barry Warsaw60f01882001-08-22 19:24:42 +00004118 PyTypeObject *type, *subtype, *staticbase;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004119 PyObject *arg0, *res;
4120
4121 if (self == NULL || !PyType_Check(self))
4122 Py_FatalError("__new__() called with non-type 'self'");
4123 type = (PyTypeObject *)self;
4124 if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004125 PyErr_Format(PyExc_TypeError,
4126 "%s.__new__(): not enough arguments",
4127 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004128 return NULL;
4129 }
4130 arg0 = PyTuple_GET_ITEM(args, 0);
4131 if (!PyType_Check(arg0)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004132 PyErr_Format(PyExc_TypeError,
4133 "%s.__new__(X): X is not a type object (%s)",
4134 type->tp_name,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004135 Py_Type(arg0)->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004136 return NULL;
4137 }
4138 subtype = (PyTypeObject *)arg0;
4139 if (!PyType_IsSubtype(subtype, type)) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004140 PyErr_Format(PyExc_TypeError,
4141 "%s.__new__(%s): %s is not a subtype of %s",
4142 type->tp_name,
4143 subtype->tp_name,
4144 subtype->tp_name,
4145 type->tp_name);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004146 return NULL;
4147 }
Barry Warsaw60f01882001-08-22 19:24:42 +00004148
4149 /* Check that the use doesn't do something silly and unsafe like
Tim Petersa427a2b2001-10-29 22:25:45 +00004150 object.__new__(dict). To do this, we check that the
Barry Warsaw60f01882001-08-22 19:24:42 +00004151 most derived base that's not a heap type is this type. */
4152 staticbase = subtype;
4153 while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
4154 staticbase = staticbase->tp_base;
Guido van Rossumd8faa362007-04-27 19:54:29 +00004155 /* If staticbase is NULL now, it is a really weird type.
4156 In the spirit of backwards compatibility (?), just shut up. */
Guido van Rossum692cdbc2006-03-10 02:04:28 +00004157 if (staticbase && staticbase->tp_new != type->tp_new) {
Barry Warsaw60f01882001-08-22 19:24:42 +00004158 PyErr_Format(PyExc_TypeError,
4159 "%s.__new__(%s) is not safe, use %s.__new__()",
4160 type->tp_name,
4161 subtype->tp_name,
4162 staticbase == NULL ? "?" : staticbase->tp_name);
4163 return NULL;
4164 }
4165
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004166 args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
4167 if (args == NULL)
4168 return NULL;
4169 res = type->tp_new(subtype, args, kwds);
4170 Py_DECREF(args);
4171 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004172}
4173
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004174static struct PyMethodDef tp_new_methoddef[] = {
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004175 {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
Neal Norwitz5dc2a372002-08-13 22:19:13 +00004176 PyDoc_STR("T.__new__(S, ...) -> "
Guido van Rossumd8faa362007-04-27 19:54:29 +00004177 "a new object with type S, a subtype of T")},
Tim Peters6d6c1a32001-08-02 04:15:00 +00004178 {0}
4179};
4180
4181static int
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004182add_tp_new_wrapper(PyTypeObject *type)
4183{
Guido van Rossumf040ede2001-08-07 16:40:56 +00004184 PyObject *func;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004185
Guido van Rossum687ae002001-10-15 22:03:32 +00004186 if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossumf040ede2001-08-07 16:40:56 +00004187 return 0;
4188 func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004189 if (func == NULL)
4190 return -1;
Raymond Hettinger8d726ee2004-06-25 22:24:35 +00004191 if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
Raymond Hettingerd56cbe52004-06-25 22:17:39 +00004192 Py_DECREF(func);
4193 return -1;
4194 }
4195 Py_DECREF(func);
4196 return 0;
Guido van Rossum0d231ed2001-08-06 16:50:37 +00004197}
4198
Guido van Rossumf040ede2001-08-07 16:40:56 +00004199/* Slot wrappers that call the corresponding __foo__ slot. See comments
4200 below at override_slots() for more explanation. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004201
Guido van Rossumdc91b992001-08-08 22:26:22 +00004202#define SLOT0(FUNCNAME, OPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004203static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004204FUNCNAME(PyObject *self) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004205{ \
Guido van Rossum5592e4d2001-08-28 18:28:21 +00004206 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004207 return call_method(self, OPSTR, &cache_str, "()"); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004208}
4209
Guido van Rossumdc91b992001-08-08 22:26:22 +00004210#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004211static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004212FUNCNAME(PyObject *self, ARG1TYPE arg1) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004213{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004214 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004215 return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004216}
4217
Guido van Rossumcd118802003-01-06 22:57:47 +00004218/* Boolean helper for SLOT1BINFULL().
4219 right.__class__ is a nontrivial subclass of left.__class__. */
4220static int
4221method_is_overloaded(PyObject *left, PyObject *right, char *name)
4222{
4223 PyObject *a, *b;
4224 int ok;
4225
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004226 b = PyObject_GetAttrString((PyObject *)(Py_Type(right)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004227 if (b == NULL) {
4228 PyErr_Clear();
4229 /* If right doesn't have it, it's not overloaded */
4230 return 0;
4231 }
4232
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004233 a = PyObject_GetAttrString((PyObject *)(Py_Type(left)), name);
Guido van Rossumcd118802003-01-06 22:57:47 +00004234 if (a == NULL) {
4235 PyErr_Clear();
4236 Py_DECREF(b);
4237 /* If right has it but left doesn't, it's overloaded */
4238 return 1;
4239 }
4240
4241 ok = PyObject_RichCompareBool(a, b, Py_NE);
4242 Py_DECREF(a);
4243 Py_DECREF(b);
4244 if (ok < 0) {
4245 PyErr_Clear();
4246 return 0;
4247 }
4248
4249 return ok;
4250}
4251
Guido van Rossumdc91b992001-08-08 22:26:22 +00004252
4253#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004254static PyObject * \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004255FUNCNAME(PyObject *self, PyObject *other) \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004256{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004257 static PyObject *cache_str, *rcache_str; \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004258 int do_other = Py_Type(self) != Py_Type(other) && \
4259 Py_Type(other)->tp_as_number != NULL && \
4260 Py_Type(other)->tp_as_number->SLOTNAME == TESTFUNC; \
4261 if (Py_Type(self)->tp_as_number != NULL && \
4262 Py_Type(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004263 PyObject *r; \
Guido van Rossum55f20992001-10-01 17:18:22 +00004264 if (do_other && \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004265 PyType_IsSubtype(Py_Type(other), Py_Type(self)) && \
Guido van Rossumcd118802003-01-06 22:57:47 +00004266 method_is_overloaded(self, other, ROPSTR)) { \
Guido van Rossum55f20992001-10-01 17:18:22 +00004267 r = call_maybe( \
4268 other, ROPSTR, &rcache_str, "(O)", self); \
4269 if (r != Py_NotImplemented) \
4270 return r; \
4271 Py_DECREF(r); \
4272 do_other = 0; \
4273 } \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004274 r = call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004275 self, OPSTR, &cache_str, "(O)", other); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004276 if (r != Py_NotImplemented || \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004277 Py_Type(other) == Py_Type(self)) \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004278 return r; \
4279 Py_DECREF(r); \
4280 } \
Guido van Rossum55f20992001-10-01 17:18:22 +00004281 if (do_other) { \
Guido van Rossumf21c6be2001-09-14 17:51:50 +00004282 return call_maybe( \
Guido van Rossum717ce002001-09-14 16:58:08 +00004283 other, ROPSTR, &rcache_str, "(O)", self); \
Guido van Rossumdc91b992001-08-08 22:26:22 +00004284 } \
4285 Py_INCREF(Py_NotImplemented); \
4286 return Py_NotImplemented; \
4287}
4288
4289#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
4290 SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
4291
4292#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
4293static PyObject * \
4294FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
4295{ \
Guido van Rossum2730b132001-08-28 18:22:14 +00004296 static PyObject *cache_str; \
Guido van Rossum717ce002001-09-14 16:58:08 +00004297 return call_method(self, OPSTR, &cache_str, \
4298 "(" ARGCODES ")", arg1, arg2); \
Tim Peters6d6c1a32001-08-02 04:15:00 +00004299}
4300
Martin v. Löwis18e16552006-02-15 17:27:45 +00004301static Py_ssize_t
Tim Peters6d6c1a32001-08-02 04:15:00 +00004302slot_sq_length(PyObject *self)
4303{
Guido van Rossum2730b132001-08-28 18:22:14 +00004304 static PyObject *len_str;
Guido van Rossum717ce002001-09-14 16:58:08 +00004305 PyObject *res = call_method(self, "__len__", &len_str, "()");
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004307
4308 if (res == NULL)
4309 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004310 len = PyInt_AsSsize_t(res);
Guido van Rossum26111622001-10-01 16:42:49 +00004311 Py_DECREF(res);
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004312 if (len < 0) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00004313 if (!PyErr_Occurred())
4314 PyErr_SetString(PyExc_ValueError,
4315 "__len__() should return >= 0");
Jeremy Hyltonf20fcf92002-07-25 16:06:15 +00004316 return -1;
4317 }
Guido van Rossum26111622001-10-01 16:42:49 +00004318 return len;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004319}
4320
Guido van Rossumf4593e02001-10-03 12:09:30 +00004321/* Super-optimized version of slot_sq_item.
4322 Other slots could do the same... */
4323static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00004324slot_sq_item(PyObject *self, Py_ssize_t i)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004325{
4326 static PyObject *getitem_str;
4327 PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
4328 descrgetfunc f;
4329
4330 if (getitem_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004331 getitem_str = PyUnicode_InternFromString("__getitem__");
Guido van Rossumf4593e02001-10-03 12:09:30 +00004332 if (getitem_str == NULL)
4333 return NULL;
4334 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004335 func = _PyType_Lookup(Py_Type(self), getitem_str);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004336 if (func != NULL) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004337 if ((f = Py_Type(func)->tp_descr_get) == NULL)
Guido van Rossumf4593e02001-10-03 12:09:30 +00004338 Py_INCREF(func);
Neal Norwitz673cd822002-10-18 16:33:13 +00004339 else {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004340 func = f(func, self, (PyObject *)(Py_Type(self)));
Neal Norwitz673cd822002-10-18 16:33:13 +00004341 if (func == NULL) {
4342 return NULL;
4343 }
4344 }
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004345 ival = PyInt_FromSsize_t(i);
Guido van Rossumf4593e02001-10-03 12:09:30 +00004346 if (ival != NULL) {
4347 args = PyTuple_New(1);
4348 if (args != NULL) {
4349 PyTuple_SET_ITEM(args, 0, ival);
4350 retval = PyObject_Call(func, args, NULL);
4351 Py_XDECREF(args);
4352 Py_XDECREF(func);
4353 return retval;
4354 }
4355 }
4356 }
4357 else {
4358 PyErr_SetObject(PyExc_AttributeError, getitem_str);
4359 }
4360 Py_XDECREF(args);
4361 Py_XDECREF(ival);
4362 Py_XDECREF(func);
4363 return NULL;
4364}
4365
Martin v. Löwis18e16552006-02-15 17:27:45 +00004366SLOT2(slot_sq_slice, "__getslice__", Py_ssize_t, Py_ssize_t, "nn")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004367
4368static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004369slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004370{
4371 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004372 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373
4374 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004375 res = call_method(self, "__delitem__", &delitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004376 "(n)", index);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004377 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004378 res = call_method(self, "__setitem__", &setitem_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004379 "(nO)", index, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004380 if (res == NULL)
4381 return -1;
4382 Py_DECREF(res);
4383 return 0;
4384}
4385
4386static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00004387slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004388{
4389 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004390 static PyObject *delslice_str, *setslice_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391
4392 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004393 res = call_method(self, "__delslice__", &delslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004394 "(nn)", i, j);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004395 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004396 res = call_method(self, "__setslice__", &setslice_str,
Thomas Wouters3fc2ca32006-04-21 11:28:17 +00004397 "(nnO)", i, j, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004398 if (res == NULL)
4399 return -1;
4400 Py_DECREF(res);
4401 return 0;
4402}
4403
4404static int
4405slot_sq_contains(PyObject *self, PyObject *value)
4406{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004407 PyObject *func, *res, *args;
Tim Petersbf9b2442003-03-23 05:35:36 +00004408 int result = -1;
4409
Guido van Rossum60718732001-08-28 17:47:51 +00004410 static PyObject *contains_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004411
Guido van Rossum55f20992001-10-01 17:18:22 +00004412 func = lookup_maybe(self, "__contains__", &contains_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004413 if (func != NULL) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004414 args = PyTuple_Pack(1, value);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004415 if (args == NULL)
4416 res = NULL;
4417 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004418 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004419 Py_DECREF(args);
4420 }
4421 Py_DECREF(func);
Tim Petersbf9b2442003-03-23 05:35:36 +00004422 if (res != NULL) {
4423 result = PyObject_IsTrue(res);
4424 Py_DECREF(res);
4425 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004426 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004427 else if (! PyErr_Occurred()) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004428 /* Possible results: -1 and 1 */
4429 result = (int)_PySequence_IterSearch(self, value,
Tim Petersbf9b2442003-03-23 05:35:36 +00004430 PY_ITERSEARCH_CONTAINS);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004431 }
Tim Petersbf9b2442003-03-23 05:35:36 +00004432 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004433}
4434
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435#define slot_mp_length slot_sq_length
4436
Guido van Rossumdc91b992001-08-08 22:26:22 +00004437SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004438
4439static int
4440slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4441{
4442 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004443 static PyObject *delitem_str, *setitem_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004444
4445 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004446 res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004447 "(O)", key);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004448 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004449 res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004450 "(OO)", key, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004451 if (res == NULL)
4452 return -1;
4453 Py_DECREF(res);
4454 return 0;
4455}
4456
Guido van Rossumdc91b992001-08-08 22:26:22 +00004457SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4458SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4459SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004460SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4461SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4462
Jeremy Hylton938ace62002-07-17 16:30:39 +00004463static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
Guido van Rossumdc91b992001-08-08 22:26:22 +00004464
4465SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4466 nb_power, "__pow__", "__rpow__")
4467
4468static PyObject *
4469slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4470{
Guido van Rossum2730b132001-08-28 18:22:14 +00004471 static PyObject *pow_str;
4472
Guido van Rossumdc91b992001-08-08 22:26:22 +00004473 if (modulus == Py_None)
4474 return slot_nb_power_binary(self, other);
Guido van Rossum23094982002-06-10 14:30:43 +00004475 /* Three-arg power doesn't use __rpow__. But ternary_op
4476 can call this when the second argument's type uses
4477 slot_nb_power, so check before calling self.__pow__. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004478 if (Py_Type(self)->tp_as_number != NULL &&
4479 Py_Type(self)->tp_as_number->nb_power == slot_nb_power) {
Guido van Rossum23094982002-06-10 14:30:43 +00004480 return call_method(self, "__pow__", &pow_str,
4481 "(OO)", other, modulus);
4482 }
4483 Py_INCREF(Py_NotImplemented);
4484 return Py_NotImplemented;
Guido van Rossumdc91b992001-08-08 22:26:22 +00004485}
4486
4487SLOT0(slot_nb_negative, "__neg__")
4488SLOT0(slot_nb_positive, "__pos__")
4489SLOT0(slot_nb_absolute, "__abs__")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004490
4491static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004492slot_nb_bool(PyObject *self)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004493{
Tim Petersea7f75d2002-12-07 21:39:16 +00004494 PyObject *func, *args;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004495 static PyObject *bool_str, *len_str;
Tim Petersea7f75d2002-12-07 21:39:16 +00004496 int result = -1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004497 int from_len = 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004498
Jack Diederich4dafcc42006-11-28 19:15:13 +00004499 func = lookup_maybe(self, "__bool__", &bool_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004500 if (func == NULL) {
Guido van Rossum55f20992001-10-01 17:18:22 +00004501 if (PyErr_Occurred())
Guido van Rossumb8f63662001-08-15 23:57:02 +00004502 return -1;
Guido van Rossum55f20992001-10-01 17:18:22 +00004503 func = lookup_maybe(self, "__len__", &len_str);
Tim Petersea7f75d2002-12-07 21:39:16 +00004504 if (func == NULL)
4505 return PyErr_Occurred() ? -1 : 1;
Jack Diederich4dafcc42006-11-28 19:15:13 +00004506 from_len = 1;
Tim Petersea7f75d2002-12-07 21:39:16 +00004507 }
4508 args = PyTuple_New(0);
4509 if (args != NULL) {
4510 PyObject *temp = PyObject_Call(func, args, NULL);
4511 Py_DECREF(args);
4512 if (temp != NULL) {
Jack Diederich4dafcc42006-11-28 19:15:13 +00004513 if (from_len) {
4514 /* enforced by slot_nb_len */
Jeremy Hylton090a3492003-06-27 16:46:45 +00004515 result = PyObject_IsTrue(temp);
Jack Diederich4dafcc42006-11-28 19:15:13 +00004516 }
4517 else if (PyBool_Check(temp)) {
4518 result = PyObject_IsTrue(temp);
4519 }
Jeremy Hylton090a3492003-06-27 16:46:45 +00004520 else {
4521 PyErr_Format(PyExc_TypeError,
Jack Diederich4dafcc42006-11-28 19:15:13 +00004522 "__bool__ should return "
4523 "bool, returned %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004524 Py_Type(temp)->tp_name);
Jeremy Hylton3e3159c2003-06-27 17:38:27 +00004525 result = -1;
Jeremy Hylton090a3492003-06-27 16:46:45 +00004526 }
Tim Petersea7f75d2002-12-07 21:39:16 +00004527 Py_DECREF(temp);
Guido van Rossum55f20992001-10-01 17:18:22 +00004528 }
Guido van Rossumb8f63662001-08-15 23:57:02 +00004529 }
Guido van Rossum55f20992001-10-01 17:18:22 +00004530 Py_DECREF(func);
Tim Petersea7f75d2002-12-07 21:39:16 +00004531 return result;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004532}
4533
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004534
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004535static PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004536slot_nb_index(PyObject *self)
4537{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004538 static PyObject *index_str;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004539 return call_method(self, "__index__", &index_str, "()");
Guido van Rossum38fff8c2006-03-07 18:50:55 +00004540}
4541
4542
Guido van Rossumdc91b992001-08-08 22:26:22 +00004543SLOT0(slot_nb_invert, "__invert__")
4544SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4545SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4546SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4547SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4548SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00004549
Guido van Rossumdc91b992001-08-08 22:26:22 +00004550SLOT0(slot_nb_int, "__int__")
4551SLOT0(slot_nb_long, "__long__")
4552SLOT0(slot_nb_float, "__float__")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004553SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4554SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4555SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
Guido van Rossumdc91b992001-08-08 22:26:22 +00004556SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
Thomas Wouterscf297e42007-02-23 15:07:44 +00004557/* Can't use SLOT1 here, because nb_inplace_power is ternary */
4558static PyObject *
4559slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
4560{
4561 static PyObject *cache_str;
4562 return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
4563}
Guido van Rossumdc91b992001-08-08 22:26:22 +00004564SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4565SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4566SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4567SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4568SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4569SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4570 "__floordiv__", "__rfloordiv__")
4571SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4572SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4573SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
Tim Peters6d6c1a32001-08-02 04:15:00 +00004574
4575static int
Guido van Rossumb8f63662001-08-15 23:57:02 +00004576half_compare(PyObject *self, PyObject *other)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004577{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004578 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004579 static PyObject *cmp_str;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004580 Py_ssize_t c;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581
Guido van Rossum60718732001-08-28 17:47:51 +00004582 func = lookup_method(self, "__cmp__", &cmp_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004583 if (func == NULL) {
4584 PyErr_Clear();
4585 }
4586 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004587 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004588 if (args == NULL)
4589 res = NULL;
4590 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004591 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004592 Py_DECREF(args);
4593 }
Raymond Hettingerab5dae32002-06-24 13:08:16 +00004594 Py_DECREF(func);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004595 if (res != Py_NotImplemented) {
4596 if (res == NULL)
4597 return -2;
4598 c = PyInt_AsLong(res);
4599 Py_DECREF(res);
4600 if (c == -1 && PyErr_Occurred())
4601 return -2;
4602 return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4603 }
4604 Py_DECREF(res);
4605 }
4606 return 2;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607}
4608
Guido van Rossumab3b0342001-09-18 20:38:53 +00004609/* This slot is published for the benefit of try_3way_compare in object.c */
4610int
4611_PyObject_SlotCompare(PyObject *self, PyObject *other)
Guido van Rossumb8f63662001-08-15 23:57:02 +00004612{
4613 int c;
4614
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004615 if (Py_Type(self)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004616 c = half_compare(self, other);
4617 if (c <= 1)
4618 return c;
4619 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004620 if (Py_Type(other)->tp_compare == _PyObject_SlotCompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004621 c = half_compare(other, self);
4622 if (c < -1)
4623 return -2;
4624 if (c <= 1)
4625 return -c;
4626 }
4627 return (void *)self < (void *)other ? -1 :
4628 (void *)self > (void *)other ? 1 : 0;
4629}
4630
4631static PyObject *
4632slot_tp_repr(PyObject *self)
4633{
4634 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004635 static PyObject *repr_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004636
Guido van Rossum60718732001-08-28 17:47:51 +00004637 func = lookup_method(self, "__repr__", &repr_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004638 if (func != NULL) {
4639 res = PyEval_CallObject(func, NULL);
4640 Py_DECREF(func);
4641 return res;
4642 }
Barry Warsaw7ce36942001-08-24 18:34:26 +00004643 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004644 return PyUnicode_FromFormat("<%s object at %p>",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004645 Py_Type(self)->tp_name, self);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004646}
4647
4648static PyObject *
4649slot_tp_str(PyObject *self)
4650{
4651 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004652 static PyObject *str_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004653
Guido van Rossum60718732001-08-28 17:47:51 +00004654 func = lookup_method(self, "__str__", &str_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004655 if (func != NULL) {
4656 res = PyEval_CallObject(func, NULL);
4657 Py_DECREF(func);
4658 return res;
4659 }
4660 else {
Walter Dörwald1ab83302007-05-18 17:15:44 +00004661 PyObject *ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004662 PyErr_Clear();
Walter Dörwald1ab83302007-05-18 17:15:44 +00004663 res = slot_tp_repr(self);
4664 if (!res)
4665 return NULL;
4666 ress = _PyUnicode_AsDefaultEncodedString(res, NULL);
4667 Py_DECREF(res);
4668 return ress;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004669 }
4670}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004671
4672static long
4673slot_tp_hash(PyObject *self)
4674{
Guido van Rossum4011a242006-08-17 23:09:57 +00004675 PyObject *func, *res;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004676 static PyObject *hash_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677 long h;
4678
Guido van Rossum60718732001-08-28 17:47:51 +00004679 func = lookup_method(self, "__hash__", &hash_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004680
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004681 if (func == Py_None) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004682 Py_DECREF(func);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004683 func = NULL;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004684 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004685
4686 if (func == NULL) {
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004687 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004688 Py_Type(self)->tp_name);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004689 return -1;
4690 }
4691
Guido van Rossum4011a242006-08-17 23:09:57 +00004692 res = PyEval_CallObject(func, NULL);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00004693 Py_DECREF(func);
4694 if (res == NULL)
4695 return -1;
4696 if (PyLong_Check(res))
4697 h = PyLong_Type.tp_hash(res);
4698 else
4699 h = PyInt_AsLong(res);
4700 Py_DECREF(res);
4701 if (h == -1 && !PyErr_Occurred())
4702 h = -2;
4703 return h;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004704}
4705
4706static PyObject *
4707slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4708{
Guido van Rossum60718732001-08-28 17:47:51 +00004709 static PyObject *call_str;
4710 PyObject *meth = lookup_method(self, "__call__", &call_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004711 PyObject *res;
4712
4713 if (meth == NULL)
4714 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004715
4716 /* PyObject_Call() will end up calling slot_tp_call() again if
4717 the object returned for __call__ has __call__ itself defined
4718 upon it. This can be an infinite recursion if you set
4719 __call__ in a class to an instance of it. */
4720 if (Py_EnterRecursiveCall(" in __call__")) {
4721 Py_DECREF(meth);
4722 return NULL;
4723 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724 res = PyObject_Call(meth, args, kwds);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004725 Py_LeaveRecursiveCall();
4726
Tim Peters6d6c1a32001-08-02 04:15:00 +00004727 Py_DECREF(meth);
4728 return res;
4729}
4730
Guido van Rossum14a6f832001-10-17 13:59:09 +00004731/* There are two slot dispatch functions for tp_getattro.
4732
4733 - slot_tp_getattro() is used when __getattribute__ is overridden
4734 but no __getattr__ hook is present;
4735
4736 - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4737
Guido van Rossumc334df52002-04-04 23:44:47 +00004738 The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4739 detects the absence of __getattr__ and then installs the simpler slot if
4740 necessary. */
Guido van Rossum14a6f832001-10-17 13:59:09 +00004741
Tim Peters6d6c1a32001-08-02 04:15:00 +00004742static PyObject *
4743slot_tp_getattro(PyObject *self, PyObject *name)
4744{
Guido van Rossum14a6f832001-10-17 13:59:09 +00004745 static PyObject *getattribute_str = NULL;
4746 return call_method(self, "__getattribute__", &getattribute_str,
4747 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004748}
4749
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004750static PyObject *
4751slot_tp_getattr_hook(PyObject *self, PyObject *name)
4752{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004753 PyTypeObject *tp = Py_Type(self);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004754 PyObject *getattr, *getattribute, *res;
4755 static PyObject *getattribute_str = NULL;
4756 static PyObject *getattr_str = NULL;
4757
4758 if (getattr_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004759 getattr_str = PyUnicode_InternFromString("__getattr__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004760 if (getattr_str == NULL)
4761 return NULL;
4762 }
4763 if (getattribute_str == NULL) {
4764 getattribute_str =
Martin v. Löwis5b222132007-06-10 09:51:05 +00004765 PyUnicode_InternFromString("__getattribute__");
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004766 if (getattribute_str == NULL)
4767 return NULL;
4768 }
4769 getattr = _PyType_Lookup(tp, getattr_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004770 if (getattr == NULL) {
Guido van Rossumd396b9c2001-10-13 20:02:41 +00004771 /* No __getattr__ hook: use a simpler dispatcher */
4772 tp->tp_getattro = slot_tp_getattro;
4773 return slot_tp_getattro(self, name);
4774 }
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004775 getattribute = _PyType_Lookup(tp, getattribute_str);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004776 if (getattribute == NULL ||
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004777 (Py_Type(getattribute) == &PyWrapperDescr_Type &&
Guido van Rossum14a6f832001-10-17 13:59:09 +00004778 ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4779 (void *)PyObject_GenericGetAttr))
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004780 res = PyObject_GenericGetAttr(self, name);
4781 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00004782 res = PyObject_CallFunctionObjArgs(getattribute, self, name, NULL);
Guido van Rossum14a6f832001-10-17 13:59:09 +00004783 if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004784 PyErr_Clear();
Thomas Wouters477c8d52006-05-27 19:21:47 +00004785 res = PyObject_CallFunctionObjArgs(getattr, self, name, NULL);
Guido van Rossum19c1cd52001-09-21 21:24:49 +00004786 }
4787 return res;
4788}
4789
Tim Peters6d6c1a32001-08-02 04:15:00 +00004790static int
4791slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4792{
4793 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004794 static PyObject *delattr_str, *setattr_str;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004795
4796 if (value == NULL)
Guido van Rossum2730b132001-08-28 18:22:14 +00004797 res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004798 "(O)", name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004799 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004800 res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004801 "(OO)", name, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004802 if (res == NULL)
4803 return -1;
4804 Py_DECREF(res);
4805 return 0;
4806}
4807
Tim Peters6d6c1a32001-08-02 04:15:00 +00004808static PyObject *
Guido van Rossumb8f63662001-08-15 23:57:02 +00004809half_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004810{
Guido van Rossumb8f63662001-08-15 23:57:02 +00004811 PyObject *func, *args, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004812 static PyObject *op_str[6];
Tim Peters6d6c1a32001-08-02 04:15:00 +00004813
Guido van Rossum60718732001-08-28 17:47:51 +00004814 func = lookup_method(self, name_op[op], &op_str[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004815 if (func == NULL) {
4816 PyErr_Clear();
4817 Py_INCREF(Py_NotImplemented);
4818 return Py_NotImplemented;
4819 }
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004820 args = PyTuple_Pack(1, other);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004821 if (args == NULL)
4822 res = NULL;
4823 else {
Guido van Rossum717ce002001-09-14 16:58:08 +00004824 res = PyObject_Call(func, args, NULL);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004825 Py_DECREF(args);
4826 }
4827 Py_DECREF(func);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004828 return res;
4829}
4830
Guido van Rossumb8f63662001-08-15 23:57:02 +00004831static PyObject *
4832slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4833{
4834 PyObject *res;
4835
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004836 if (Py_Type(self)->tp_richcompare == slot_tp_richcompare) {
Guido van Rossumb8f63662001-08-15 23:57:02 +00004837 res = half_richcompare(self, other, op);
4838 if (res != Py_NotImplemented)
4839 return res;
4840 Py_DECREF(res);
4841 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004842 if (Py_Type(other)->tp_richcompare == slot_tp_richcompare) {
Tim Petersf4aca752004-09-23 02:39:37 +00004843 res = half_richcompare(other, self, _Py_SwappedOp[op]);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004844 if (res != Py_NotImplemented) {
4845 return res;
4846 }
4847 Py_DECREF(res);
4848 }
4849 Py_INCREF(Py_NotImplemented);
4850 return Py_NotImplemented;
4851}
4852
4853static PyObject *
4854slot_tp_iter(PyObject *self)
4855{
4856 PyObject *func, *res;
Guido van Rossum60718732001-08-28 17:47:51 +00004857 static PyObject *iter_str, *getitem_str;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004858
Guido van Rossum60718732001-08-28 17:47:51 +00004859 func = lookup_method(self, "__iter__", &iter_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004860 if (func != NULL) {
Guido van Rossum84b2bed2002-08-16 17:01:09 +00004861 PyObject *args;
4862 args = res = PyTuple_New(0);
4863 if (args != NULL) {
4864 res = PyObject_Call(func, args, NULL);
4865 Py_DECREF(args);
4866 }
4867 Py_DECREF(func);
4868 return res;
Guido van Rossumb8f63662001-08-15 23:57:02 +00004869 }
4870 PyErr_Clear();
Guido van Rossum60718732001-08-28 17:47:51 +00004871 func = lookup_method(self, "__getitem__", &getitem_str);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004872 if (func == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004873 PyErr_Format(PyExc_TypeError,
4874 "'%.200s' object is not iterable",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004875 Py_Type(self)->tp_name);
Guido van Rossumb8f63662001-08-15 23:57:02 +00004876 return NULL;
4877 }
4878 Py_DECREF(func);
4879 return PySeqIter_New(self);
4880}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004881
4882static PyObject *
4883slot_tp_iternext(PyObject *self)
4884{
Guido van Rossum2730b132001-08-28 18:22:14 +00004885 static PyObject *next_str;
Georg Brandla18af4e2007-04-21 15:47:16 +00004886 return call_method(self, "__next__", &next_str, "()");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004887}
4888
Guido van Rossum1a493502001-08-17 16:47:50 +00004889static PyObject *
4890slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4891{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004892 PyTypeObject *tp = Py_Type(self);
Guido van Rossum1a493502001-08-17 16:47:50 +00004893 PyObject *get;
4894 static PyObject *get_str = NULL;
4895
4896 if (get_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004897 get_str = PyUnicode_InternFromString("__get__");
Guido van Rossum1a493502001-08-17 16:47:50 +00004898 if (get_str == NULL)
4899 return NULL;
4900 }
4901 get = _PyType_Lookup(tp, get_str);
4902 if (get == NULL) {
4903 /* Avoid further slowdowns */
4904 if (tp->tp_descr_get == slot_tp_descr_get)
4905 tp->tp_descr_get = NULL;
4906 Py_INCREF(self);
4907 return self;
4908 }
Guido van Rossum2c252392001-08-24 10:13:31 +00004909 if (obj == NULL)
4910 obj = Py_None;
4911 if (type == NULL)
4912 type = Py_None;
Thomas Wouters477c8d52006-05-27 19:21:47 +00004913 return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
Guido van Rossum1a493502001-08-17 16:47:50 +00004914}
Tim Peters6d6c1a32001-08-02 04:15:00 +00004915
4916static int
4917slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4918{
Guido van Rossum2c252392001-08-24 10:13:31 +00004919 PyObject *res;
Guido van Rossum2730b132001-08-28 18:22:14 +00004920 static PyObject *del_str, *set_str;
Guido van Rossum2c252392001-08-24 10:13:31 +00004921
4922 if (value == NULL)
Guido van Rossum1d5b3f22001-12-03 00:08:33 +00004923 res = call_method(self, "__delete__", &del_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004924 "(O)", target);
Guido van Rossum2c252392001-08-24 10:13:31 +00004925 else
Guido van Rossum2730b132001-08-28 18:22:14 +00004926 res = call_method(self, "__set__", &set_str,
Guido van Rossum717ce002001-09-14 16:58:08 +00004927 "(OO)", target, value);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004928 if (res == NULL)
4929 return -1;
4930 Py_DECREF(res);
4931 return 0;
4932}
4933
4934static int
4935slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4936{
Guido van Rossum60718732001-08-28 17:47:51 +00004937 static PyObject *init_str;
4938 PyObject *meth = lookup_method(self, "__init__", &init_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939 PyObject *res;
4940
4941 if (meth == NULL)
4942 return -1;
4943 res = PyObject_Call(meth, args, kwds);
4944 Py_DECREF(meth);
4945 if (res == NULL)
4946 return -1;
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004947 if (res != Py_None) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004948 PyErr_Format(PyExc_TypeError,
4949 "__init__() should return None, not '%.200s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004950 Py_Type(res)->tp_name);
Raymond Hettingerb67cc802005-03-03 16:45:19 +00004951 Py_DECREF(res);
4952 return -1;
4953 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004954 Py_DECREF(res);
4955 return 0;
4956}
4957
4958static PyObject *
4959slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4960{
Guido van Rossum7bed2132002-08-08 21:57:53 +00004961 static PyObject *new_str;
4962 PyObject *func;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004963 PyObject *newargs, *x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004964 Py_ssize_t i, n;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004965
Guido van Rossum7bed2132002-08-08 21:57:53 +00004966 if (new_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00004967 new_str = PyUnicode_InternFromString("__new__");
Guido van Rossum7bed2132002-08-08 21:57:53 +00004968 if (new_str == NULL)
4969 return NULL;
4970 }
4971 func = PyObject_GetAttr((PyObject *)type, new_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004972 if (func == NULL)
4973 return NULL;
4974 assert(PyTuple_Check(args));
4975 n = PyTuple_GET_SIZE(args);
4976 newargs = PyTuple_New(n+1);
4977 if (newargs == NULL)
4978 return NULL;
4979 Py_INCREF(type);
4980 PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4981 for (i = 0; i < n; i++) {
4982 x = PyTuple_GET_ITEM(args, i);
4983 Py_INCREF(x);
4984 PyTuple_SET_ITEM(newargs, i+1, x);
4985 }
4986 x = PyObject_Call(func, newargs, kwds);
Guido van Rossum25d18072001-10-01 15:55:28 +00004987 Py_DECREF(newargs);
Tim Peters6d6c1a32001-08-02 04:15:00 +00004988 Py_DECREF(func);
4989 return x;
4990}
4991
Guido van Rossumfebd61d2002-08-08 20:55:20 +00004992static void
4993slot_tp_del(PyObject *self)
4994{
4995 static PyObject *del_str = NULL;
4996 PyObject *del, *res;
4997 PyObject *error_type, *error_value, *error_traceback;
4998
4999 /* Temporarily resurrect the object. */
5000 assert(self->ob_refcnt == 0);
5001 self->ob_refcnt = 1;
5002
5003 /* Save the current exception, if any. */
5004 PyErr_Fetch(&error_type, &error_value, &error_traceback);
5005
5006 /* Execute __del__ method, if any. */
5007 del = lookup_maybe(self, "__del__", &del_str);
5008 if (del != NULL) {
5009 res = PyEval_CallObject(del, NULL);
5010 if (res == NULL)
5011 PyErr_WriteUnraisable(del);
5012 else
5013 Py_DECREF(res);
5014 Py_DECREF(del);
5015 }
5016
5017 /* Restore the saved exception. */
5018 PyErr_Restore(error_type, error_value, error_traceback);
5019
5020 /* Undo the temporary resurrection; can't use DECREF here, it would
5021 * cause a recursive call.
5022 */
5023 assert(self->ob_refcnt > 0);
5024 if (--self->ob_refcnt == 0)
5025 return; /* this is the normal path out */
5026
5027 /* __del__ resurrected it! Make it look like the original Py_DECREF
5028 * never happened.
5029 */
5030 {
Martin v. Löwis725507b2006-03-07 12:08:51 +00005031 Py_ssize_t refcnt = self->ob_refcnt;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005032 _Py_NewReference(self);
5033 self->ob_refcnt = refcnt;
5034 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005035 assert(!PyType_IS_GC(Py_Type(self)) ||
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005036 _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
Michael W. Hudson3f3b6682004-08-03 10:21:03 +00005037 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
5038 * we need to undo that. */
5039 _Py_DEC_REFTOTAL;
5040 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
5041 * chain, so no more to do there.
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005042 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
5043 * _Py_NewReference bumped tp_allocs: both of those need to be
5044 * undone.
5045 */
5046#ifdef COUNT_ALLOCS
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005047 --Py_Type(self)->tp_frees;
5048 --Py_Type(self)->tp_allocs;
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005049#endif
5050}
5051
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005052
5053/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
Tim Petersbf9b2442003-03-23 05:35:36 +00005054 functions. The offsets here are relative to the 'PyHeapTypeObject'
Guido van Rossume5c691a2003-03-07 15:13:17 +00005055 structure, which incorporates the additional structures used for numbers,
5056 sequences and mappings.
5057 Note that multiple names may map to the same slot (e.g. __eq__,
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005058 __ne__ etc. all map to tp_richcompare) and one name may map to multiple
Guido van Rossumc334df52002-04-04 23:44:47 +00005059 slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
5060 terminated with an all-zero entry. (This table is further initialized and
5061 sorted in init_slotdefs() below.) */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005062
Guido van Rossum6d204072001-10-21 00:44:31 +00005063typedef struct wrapperbase slotdef;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005064
5065#undef TPSLOT
Guido van Rossumc8e56452001-10-22 00:43:43 +00005066#undef FLSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005067#undef ETSLOT
5068#undef SQSLOT
5069#undef MPSLOT
5070#undef NBSLOT
Guido van Rossum6d204072001-10-21 00:44:31 +00005071#undef UNSLOT
5072#undef IBSLOT
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005073#undef BINSLOT
5074#undef RBINSLOT
5075
Guido van Rossum6d204072001-10-21 00:44:31 +00005076#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005077 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
5078 PyDoc_STR(DOC)}
Guido van Rossumc8e56452001-10-22 00:43:43 +00005079#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
5080 {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005081 PyDoc_STR(DOC), FLAGS}
Guido van Rossum6d204072001-10-21 00:44:31 +00005082#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
Guido van Rossume5c691a2003-03-07 15:13:17 +00005083 {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
Neal Norwitzd47714a2002-08-13 19:01:38 +00005084 PyDoc_STR(DOC)}
Guido van Rossum6d204072001-10-21 00:44:31 +00005085#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5086 ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
5087#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5088 ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
5089#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5090 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
5091#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5092 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5093 "x." NAME "() <==> " DOC)
5094#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
5095 ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
5096 "x." NAME "(y) <==> x" DOC "y")
5097#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
5098 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5099 "x." NAME "(y) <==> x" DOC "y")
5100#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
5101 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5102 "x." NAME "(y) <==> y" DOC "x")
Anthony Baxter56616992005-06-03 14:12:21 +00005103#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5104 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
5105 "x." NAME "(y) <==> " DOC)
5106#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
5107 ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
5108 "x." NAME "(y) <==> " DOC)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005109
5110static slotdef slotdefs[] = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00005111 SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005112 "x.__len__() <==> len(x)"),
Armin Rigofd163f92005-12-29 15:59:19 +00005113 /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
5114 The logic in abstract.c always falls back to nb_add/nb_multiply in
5115 this case. Defining both the nb_* and the sq_* slots to call the
5116 user-defined methods has unexpected side-effects, as shown by
5117 test_descr.notimplemented() */
5118 SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005119 "x.__add__(y) <==> x+y"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005120 SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005121 "x.__mul__(n) <==> x*n"),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005122 SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005123 "x.__rmul__(n) <==> n*x"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005124 SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
5125 "x.__getitem__(y) <==> x[y]"),
Martin v. Löwis18e16552006-02-15 17:27:45 +00005126 SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
Brett Cannon154da9b2003-05-20 02:30:04 +00005127 "x.__getslice__(i, j) <==> x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005128 \n\
5129 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005130 SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005131 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005132 SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
Brett Cannonbe67d872003-05-20 02:40:12 +00005133 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005134 SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
Martin v. Löwis18e16552006-02-15 17:27:45 +00005135 wrap_ssizessizeobjargproc,
Brett Cannonbe67d872003-05-20 02:40:12 +00005136 "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005137 \n\
5138 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005139 SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
Brett Cannonbe67d872003-05-20 02:40:12 +00005140 "x.__delslice__(i, j) <==> del x[i:j]\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00005141 \n\
5142 Use of negative indices is not supported."),
Guido van Rossum6d204072001-10-21 00:44:31 +00005143 SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
5144 "x.__contains__(y) <==> y in x"),
Armin Rigofd163f92005-12-29 15:59:19 +00005145 SQSLOT("__iadd__", sq_inplace_concat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005146 wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
Armin Rigofd163f92005-12-29 15:59:19 +00005147 SQSLOT("__imul__", sq_inplace_repeat, NULL,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005148 wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005149
Martin v. Löwis18e16552006-02-15 17:27:45 +00005150 MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
Guido van Rossum6d204072001-10-21 00:44:31 +00005151 "x.__len__() <==> len(x)"),
Guido van Rossumfd38f8e2001-10-09 20:17:57 +00005152 MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005153 wrap_binaryfunc,
5154 "x.__getitem__(y) <==> x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005155 MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005156 wrap_objobjargproc,
5157 "x.__setitem__(i, y) <==> x[i]=y"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005158 MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
Guido van Rossum6d204072001-10-21 00:44:31 +00005159 wrap_delitem,
5160 "x.__delitem__(y) <==> del x[y]"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005161
Guido van Rossum6d204072001-10-21 00:44:31 +00005162 BINSLOT("__add__", nb_add, slot_nb_add,
5163 "+"),
5164 RBINSLOT("__radd__", nb_add, slot_nb_add,
5165 "+"),
5166 BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
5167 "-"),
5168 RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
5169 "-"),
5170 BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
5171 "*"),
5172 RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
5173 "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005174 BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
5175 "%"),
5176 RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
5177 "%"),
Anthony Baxter56616992005-06-03 14:12:21 +00005178 BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005179 "divmod(x, y)"),
Anthony Baxter56616992005-06-03 14:12:21 +00005180 RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
Guido van Rossum6d204072001-10-21 00:44:31 +00005181 "divmod(y, x)"),
5182 NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
5183 "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
5184 NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
5185 "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
5186 UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
5187 UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
5188 UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
5189 "abs(x)"),
Jack Diederich4dafcc42006-11-28 19:15:13 +00005190 UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred,
Guido van Rossum6d204072001-10-21 00:44:31 +00005191 "x != 0"),
5192 UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
5193 BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
5194 RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
5195 BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
5196 RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
5197 BINSLOT("__and__", nb_and, slot_nb_and, "&"),
5198 RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
5199 BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
5200 RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
5201 BINSLOT("__or__", nb_or, slot_nb_or, "|"),
5202 RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005203 UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
5204 "int(x)"),
5205 UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
5206 "long(x)"),
5207 UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
5208 "float(x)"),
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00005209 NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
Guido van Rossum38fff8c2006-03-07 18:50:55 +00005210 "x[y:z] <==> x[y.__index__():z.__index__()]"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005211 IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
5212 wrap_binaryfunc, "+"),
5213 IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
5214 wrap_binaryfunc, "-"),
5215 IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
5216 wrap_binaryfunc, "*"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005217 IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
5218 wrap_binaryfunc, "%"),
5219 IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
Guido van Rossum6e5680f2002-10-15 01:01:53 +00005220 wrap_binaryfunc, "**"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005221 IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
5222 wrap_binaryfunc, "<<"),
5223 IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
5224 wrap_binaryfunc, ">>"),
5225 IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
5226 wrap_binaryfunc, "&"),
5227 IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
5228 wrap_binaryfunc, "^"),
5229 IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
5230 wrap_binaryfunc, "|"),
5231 BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5232 RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
5233 BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
5234 RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
5235 IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
5236 slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
5237 IBSLOT("__itruediv__", nb_inplace_true_divide,
5238 slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005239
Guido van Rossum6d204072001-10-21 00:44:31 +00005240 TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
5241 "x.__str__() <==> str(x)"),
5242 TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
5243 "x.__repr__() <==> repr(x)"),
5244 TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
5245 "x.__cmp__(y) <==> cmp(x,y)"),
5246 TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
5247 "x.__hash__() <==> hash(x)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005248 FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
5249 "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005250 TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
Guido van Rossum6d204072001-10-21 00:44:31 +00005251 wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
5252 TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
5253 TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
5254 TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
5255 TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
5256 "x.__setattr__('name', value) <==> x.name = value"),
5257 TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
5258 TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
5259 "x.__delattr__('name') <==> del x.name"),
5260 TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
5261 TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
5262 "x.__lt__(y) <==> x<y"),
5263 TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
5264 "x.__le__(y) <==> x<=y"),
5265 TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
5266 "x.__eq__(y) <==> x==y"),
5267 TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
5268 "x.__ne__(y) <==> x!=y"),
5269 TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
5270 "x.__gt__(y) <==> x>y"),
5271 TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
5272 "x.__ge__(y) <==> x>=y"),
5273 TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
5274 "x.__iter__() <==> iter(x)"),
Georg Brandla18af4e2007-04-21 15:47:16 +00005275 TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next,
5276 "x.__next__() <==> next(x)"),
Guido van Rossum6d204072001-10-21 00:44:31 +00005277 TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
5278 "descr.__get__(obj[, type]) -> value"),
5279 TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
5280 "descr.__set__(obj, value)"),
Guido van Rossum0dbab4c52002-08-01 14:39:25 +00005281 TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
5282 wrap_descr_delete, "descr.__delete__(obj)"),
Guido van Rossumc8e56452001-10-22 00:43:43 +00005283 FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
Guido van Rossum6d204072001-10-21 00:44:31 +00005284 "x.__init__(...) initializes x; "
Guido van Rossumc8e56452001-10-22 00:43:43 +00005285 "see x.__class__.__doc__ for signature",
5286 PyWrapperFlag_KEYWORDS),
5287 TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
Guido van Rossumfebd61d2002-08-08 20:55:20 +00005288 TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005289 {NULL}
5290};
5291
Guido van Rossumc334df52002-04-04 23:44:47 +00005292/* Given a type pointer and an offset gotten from a slotdef entry, return a
Guido van Rossumd8faa362007-04-27 19:54:29 +00005293 pointer to the actual slot. This is not quite the same as simply adding
Guido van Rossumc334df52002-04-04 23:44:47 +00005294 the offset to the type pointer, since it takes care to indirect through the
5295 proper indirection pointer (as_buffer, etc.); it returns NULL if the
5296 indirection pointer is NULL. */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005297static void **
Martin v. Löwis18e16552006-02-15 17:27:45 +00005298slotptr(PyTypeObject *type, int ioffset)
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005299{
5300 char *ptr;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005301 long offset = ioffset;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005302
Guido van Rossume5c691a2003-03-07 15:13:17 +00005303 /* Note: this depends on the order of the members of PyHeapTypeObject! */
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005304 assert(offset >= 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005305 assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
5306 if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
5307 ptr = (char *)type->tp_as_sequence;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005308 offset -= offsetof(PyHeapTypeObject, as_sequence);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005309 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005310 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
5311 ptr = (char *)type->tp_as_mapping;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005312 offset -= offsetof(PyHeapTypeObject, as_mapping);
Guido van Rossum09638c12002-06-13 19:17:46 +00005313 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005314 else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
5315 ptr = (char *)type->tp_as_number;
Guido van Rossume5c691a2003-03-07 15:13:17 +00005316 offset -= offsetof(PyHeapTypeObject, as_number);
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005317 }
5318 else {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005319 ptr = (char *)type;
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005320 }
5321 if (ptr != NULL)
5322 ptr += offset;
5323 return (void **)ptr;
5324}
Guido van Rossumf040ede2001-08-07 16:40:56 +00005325
Guido van Rossumc334df52002-04-04 23:44:47 +00005326/* Length of array of slotdef pointers used to store slots with the
5327 same __name__. There should be at most MAX_EQUIV-1 slotdef entries with
5328 the same __name__, for any __name__. Since that's a static property, it is
5329 appropriate to declare fixed-size arrays for this. */
5330#define MAX_EQUIV 10
5331
5332/* Return a slot pointer for a given name, but ONLY if the attribute has
5333 exactly one slot function. The name must be an interned string. */
5334static void **
5335resolve_slotdups(PyTypeObject *type, PyObject *name)
5336{
5337 /* XXX Maybe this could be optimized more -- but is it worth it? */
5338
5339 /* pname and ptrs act as a little cache */
5340 static PyObject *pname;
5341 static slotdef *ptrs[MAX_EQUIV];
5342 slotdef *p, **pp;
5343 void **res, **ptr;
5344
5345 if (pname != name) {
5346 /* Collect all slotdefs that match name into ptrs. */
5347 pname = name;
5348 pp = ptrs;
5349 for (p = slotdefs; p->name_strobj; p++) {
5350 if (p->name_strobj == name)
5351 *pp++ = p;
5352 }
5353 *pp = NULL;
5354 }
5355
5356 /* Look in all matching slots of the type; if exactly one of these has
Guido van Rossumd8faa362007-04-27 19:54:29 +00005357 a filled-in slot, return its value. Otherwise return NULL. */
Guido van Rossumc334df52002-04-04 23:44:47 +00005358 res = NULL;
5359 for (pp = ptrs; *pp; pp++) {
5360 ptr = slotptr(type, (*pp)->offset);
5361 if (ptr == NULL || *ptr == NULL)
5362 continue;
5363 if (res != NULL)
5364 return NULL;
5365 res = ptr;
5366 }
5367 return res;
5368}
5369
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005370/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
Guido van Rossumc334df52002-04-04 23:44:47 +00005371 does some incredibly complex thinking and then sticks something into the
5372 slot. (It sees if the adjacent slotdefs for the same slot have conflicting
5373 interests, and then stores a generic wrapper or a specific function into
5374 the slot.) Return a pointer to the next slotdef with a different offset,
5375 because that's convenient for fixup_slot_dispatchers(). */
5376static slotdef *
5377update_one_slot(PyTypeObject *type, slotdef *p)
5378{
5379 PyObject *descr;
5380 PyWrapperDescrObject *d;
5381 void *generic = NULL, *specific = NULL;
5382 int use_generic = 0;
5383 int offset = p->offset;
5384 void **ptr = slotptr(type, offset);
5385
5386 if (ptr == NULL) {
5387 do {
5388 ++p;
5389 } while (p->offset == offset);
5390 return p;
5391 }
5392 do {
5393 descr = _PyType_Lookup(type, p->name_strobj);
5394 if (descr == NULL)
5395 continue;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005396 if (Py_Type(descr) == &PyWrapperDescr_Type) {
Guido van Rossumc334df52002-04-04 23:44:47 +00005397 void **tptr = resolve_slotdups(type, p->name_strobj);
5398 if (tptr == NULL || tptr == ptr)
5399 generic = p->function;
5400 d = (PyWrapperDescrObject *)descr;
5401 if (d->d_base->wrapper == p->wrapper &&
5402 PyType_IsSubtype(type, d->d_type))
5403 {
5404 if (specific == NULL ||
5405 specific == d->d_wrapped)
5406 specific = d->d_wrapped;
5407 else
5408 use_generic = 1;
5409 }
5410 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005411 else if (Py_Type(descr) == &PyCFunction_Type &&
Guido van Rossum721f62e2002-08-09 02:14:34 +00005412 PyCFunction_GET_FUNCTION(descr) ==
5413 (PyCFunction)tp_new_wrapper &&
5414 strcmp(p->name, "__new__") == 0)
5415 {
5416 /* The __new__ wrapper is not a wrapper descriptor,
5417 so must be special-cased differently.
5418 If we don't do this, creating an instance will
5419 always use slot_tp_new which will look up
5420 __new__ in the MRO which will call tp_new_wrapper
5421 which will look through the base classes looking
5422 for a static base and call its tp_new (usually
5423 PyType_GenericNew), after performing various
5424 sanity checks and constructing a new argument
5425 list. Cut all that nonsense short -- this speeds
5426 up instance creation tremendously. */
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005427 specific = (void *)type->tp_new;
Guido van Rossum721f62e2002-08-09 02:14:34 +00005428 /* XXX I'm not 100% sure that there isn't a hole
5429 in this reasoning that requires additional
5430 sanity checks. I'll buy the first person to
5431 point out a bug in this reasoning a beer. */
5432 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005433 else {
5434 use_generic = 1;
5435 generic = p->function;
5436 }
5437 } while ((++p)->offset == offset);
5438 if (specific && !use_generic)
5439 *ptr = specific;
5440 else
5441 *ptr = generic;
5442 return p;
5443}
5444
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005445/* In the type, update the slots whose slotdefs are gathered in the pp array.
5446 This is a callback for update_subclasses(). */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005447static int
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005448update_slots_callback(PyTypeObject *type, void *data)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005449{
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005450 slotdef **pp = (slotdef **)data;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005451
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005452 for (; *pp; pp++)
Guido van Rossumc334df52002-04-04 23:44:47 +00005453 update_one_slot(type, *pp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005454 return 0;
5455}
5456
Guido van Rossumc334df52002-04-04 23:44:47 +00005457/* Comparison function for qsort() to compare slotdefs by their offset, and
5458 for equal offset by their address (to force a stable sort). */
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005459static int
5460slotdef_cmp(const void *aa, const void *bb)
5461{
5462 const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5463 int c = a->offset - b->offset;
5464 if (c != 0)
5465 return c;
5466 else
Martin v. Löwis18e16552006-02-15 17:27:45 +00005467 /* Cannot use a-b, as this gives off_t,
5468 which may lose precision when converted to int. */
5469 return (a > b) ? 1 : (a < b) ? -1 : 0;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005470}
5471
Guido van Rossumc334df52002-04-04 23:44:47 +00005472/* Initialize the slotdefs table by adding interned string objects for the
5473 names and sorting the entries. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005474static void
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005475init_slotdefs(void)
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005476{
5477 slotdef *p;
5478 static int initialized = 0;
5479
5480 if (initialized)
5481 return;
5482 for (p = slotdefs; p->name; p++) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005483 p->name_strobj = PyUnicode_InternFromString(p->name);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005484 if (!p->name_strobj)
Guido van Rossumc334df52002-04-04 23:44:47 +00005485 Py_FatalError("Out of memory interning slotdef names");
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005486 }
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005487 qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5488 slotdef_cmp);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005489 initialized = 1;
5490}
5491
Guido van Rossumc334df52002-04-04 23:44:47 +00005492/* Update the slots after assignment to a class (type) attribute. */
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005493static int
5494update_slot(PyTypeObject *type, PyObject *name)
5495{
Guido van Rossumc334df52002-04-04 23:44:47 +00005496 slotdef *ptrs[MAX_EQUIV];
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005497 slotdef *p;
5498 slotdef **pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005499 int offset;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005500
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005501 init_slotdefs();
5502 pp = ptrs;
5503 for (p = slotdefs; p->name; p++) {
5504 /* XXX assume name is interned! */
5505 if (p->name_strobj == name)
5506 *pp++ = p;
5507 }
5508 *pp = NULL;
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005509 for (pp = ptrs; *pp; pp++) {
5510 p = *pp;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005511 offset = p->offset;
5512 while (p > slotdefs && (p-1)->offset == offset)
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005513 --p;
Guido van Rossumb85a8b72001-10-16 17:00:48 +00005514 *pp = p;
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005515 }
Guido van Rossumc334df52002-04-04 23:44:47 +00005516 if (ptrs[0] == NULL)
5517 return 0; /* Not an attribute that affects any slots */
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005518 return update_subclasses(type, name,
5519 update_slots_callback, (void *)ptrs);
Guido van Rossum875eeaa2001-10-11 18:33:53 +00005520}
5521
Guido van Rossumc334df52002-04-04 23:44:47 +00005522/* Store the proper functions in the slot dispatches at class (type)
5523 definition time, based upon which operations the class overrides in its
5524 dict. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00005525static void
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005526fixup_slot_dispatchers(PyTypeObject *type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00005527{
Guido van Rossum7b9144b2001-10-09 19:39:46 +00005528 slotdef *p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00005529
Guido van Rossumd396b9c2001-10-13 20:02:41 +00005530 init_slotdefs();
Guido van Rossumc334df52002-04-04 23:44:47 +00005531 for (p = slotdefs; p->name; )
5532 p = update_one_slot(type, p);
Tim Peters6d6c1a32001-08-02 04:15:00 +00005533}
Guido van Rossum705f0f52001-08-24 16:47:00 +00005534
Michael W. Hudson98bbc492002-11-26 14:47:27 +00005535static void
5536update_all_slots(PyTypeObject* type)
5537{
5538 slotdef *p;
5539
5540 init_slotdefs();
5541 for (p = slotdefs; p->name; p++) {
5542 /* update_slot returns int but can't actually fail */
5543 update_slot(type, p->name_strobj);
5544 }
5545}
5546
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005547/* recurse_down_subclasses() and update_subclasses() are mutually
5548 recursive functions to call a callback for all subclasses,
5549 but refraining from recursing into subclasses that define 'name'. */
5550
5551static int
5552update_subclasses(PyTypeObject *type, PyObject *name,
5553 update_callback callback, void *data)
5554{
5555 if (callback(type, data) < 0)
5556 return -1;
5557 return recurse_down_subclasses(type, name, callback, data);
5558}
5559
5560static int
5561recurse_down_subclasses(PyTypeObject *type, PyObject *name,
5562 update_callback callback, void *data)
5563{
5564 PyTypeObject *subclass;
5565 PyObject *ref, *subclasses, *dict;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005566 Py_ssize_t i, n;
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005567
5568 subclasses = type->tp_subclasses;
5569 if (subclasses == NULL)
5570 return 0;
5571 assert(PyList_Check(subclasses));
5572 n = PyList_GET_SIZE(subclasses);
5573 for (i = 0; i < n; i++) {
5574 ref = PyList_GET_ITEM(subclasses, i);
5575 assert(PyWeakref_CheckRef(ref));
5576 subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5577 assert(subclass != NULL);
5578 if ((PyObject *)subclass == Py_None)
5579 continue;
5580 assert(PyType_Check(subclass));
5581 /* Avoid recursing down into unaffected classes */
5582 dict = subclass->tp_dict;
5583 if (dict != NULL && PyDict_Check(dict) &&
5584 PyDict_GetItem(dict, name) != NULL)
5585 continue;
5586 if (update_subclasses(subclass, name, callback, data) < 0)
5587 return -1;
5588 }
5589 return 0;
5590}
5591
Guido van Rossum6d204072001-10-21 00:44:31 +00005592/* This function is called by PyType_Ready() to populate the type's
5593 dictionary with method descriptors for function slots. For each
Guido van Rossum09638c12002-06-13 19:17:46 +00005594 function slot (like tp_repr) that's defined in the type, one or more
5595 corresponding descriptors are added in the type's tp_dict dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +00005596 under the appropriate name (like __repr__). Some function slots
Guido van Rossum09638c12002-06-13 19:17:46 +00005597 cause more than one descriptor to be added (for example, the nb_add
5598 slot adds both __add__ and __radd__ descriptors) and some function
5599 slots compete for the same descriptor (for example both sq_item and
5600 mp_subscript generate a __getitem__ descriptor).
5601
Guido van Rossumd8faa362007-04-27 19:54:29 +00005602 In the latter case, the first slotdef entry encoutered wins. Since
Tim Petersbf9b2442003-03-23 05:35:36 +00005603 slotdef entries are sorted by the offset of the slot in the
Guido van Rossume5c691a2003-03-07 15:13:17 +00005604 PyHeapTypeObject, this gives us some control over disambiguating
Guido van Rossum8d24ee92003-03-24 23:49:49 +00005605 between competing slots: the members of PyHeapTypeObject are listed
5606 from most general to least general, so the most general slot is
5607 preferred. In particular, because as_mapping comes before as_sequence,
5608 for a type that defines both mp_subscript and sq_item, mp_subscript
5609 wins.
Guido van Rossum09638c12002-06-13 19:17:46 +00005610
5611 This only adds new descriptors and doesn't overwrite entries in
5612 tp_dict that were previously defined. The descriptors contain a
5613 reference to the C function they must call, so that it's safe if they
5614 are copied into a subtype's __dict__ and the subtype has a different
5615 C function in its slot -- calling the method defined by the
5616 descriptor will call the C function that was used to create it,
5617 rather than the C function present in the slot when it is called.
5618 (This is important because a subtype may have a C function in the
5619 slot that calls the method from the dictionary, and we want to avoid
5620 infinite recursion here.) */
Guido van Rossum6d204072001-10-21 00:44:31 +00005621
5622static int
5623add_operators(PyTypeObject *type)
5624{
5625 PyObject *dict = type->tp_dict;
5626 slotdef *p;
5627 PyObject *descr;
5628 void **ptr;
5629
5630 init_slotdefs();
5631 for (p = slotdefs; p->name; p++) {
5632 if (p->wrapper == NULL)
5633 continue;
5634 ptr = slotptr(type, p->offset);
5635 if (!ptr || !*ptr)
5636 continue;
5637 if (PyDict_GetItem(dict, p->name_strobj))
5638 continue;
5639 descr = PyDescr_NewWrapper(type, p, *ptr);
5640 if (descr == NULL)
5641 return -1;
5642 if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5643 return -1;
5644 Py_DECREF(descr);
5645 }
5646 if (type->tp_new != NULL) {
5647 if (add_tp_new_wrapper(type) < 0)
5648 return -1;
5649 }
5650 return 0;
5651}
5652
Guido van Rossum705f0f52001-08-24 16:47:00 +00005653
5654/* Cooperative 'super' */
5655
5656typedef struct {
5657 PyObject_HEAD
Guido van Rossume705ef12001-08-29 15:47:06 +00005658 PyTypeObject *type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005659 PyObject *obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005660 PyTypeObject *obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005661} superobject;
5662
Guido van Rossum6f799372001-09-20 20:46:19 +00005663static PyMemberDef super_members[] = {
5664 {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5665 "the class invoking super()"},
5666 {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
5667 "the instance invoking super(); may be None"},
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005668 {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005669 "the type of the instance invoking super(); may be None"},
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005670 {0}
5671};
5672
Guido van Rossum705f0f52001-08-24 16:47:00 +00005673static void
5674super_dealloc(PyObject *self)
5675{
5676 superobject *su = (superobject *)self;
5677
Guido van Rossum048eb752001-10-02 21:24:57 +00005678 _PyObject_GC_UNTRACK(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005679 Py_XDECREF(su->obj);
5680 Py_XDECREF(su->type);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005681 Py_XDECREF(su->obj_type);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005682 Py_Type(self)->tp_free(self);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005683}
5684
5685static PyObject *
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005686super_repr(PyObject *self)
5687{
5688 superobject *su = (superobject *)self;
5689
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005690 if (su->obj_type)
Walter Dörwald1ab83302007-05-18 17:15:44 +00005691 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005692 "<super: <class '%s'>, <%s object>>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005693 su->type ? su->type->tp_name : "NULL",
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005694 su->obj_type->tp_name);
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005695 else
Walter Dörwald1ab83302007-05-18 17:15:44 +00005696 return PyUnicode_FromFormat(
Guido van Rossuma4cb7882001-09-25 03:56:29 +00005697 "<super: <class '%s'>, NULL>",
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005698 su->type ? su->type->tp_name : "NULL");
5699}
5700
5701static PyObject *
Guido van Rossum705f0f52001-08-24 16:47:00 +00005702super_getattro(PyObject *self, PyObject *name)
5703{
5704 superobject *su = (superobject *)self;
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005705 int skip = su->obj_type == NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005706
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005707 if (!skip) {
5708 /* We want __class__ to return the class of the super object
5709 (i.e. super, or a subclass), not the class of su->obj. */
Martin v. Löwis5b222132007-06-10 09:51:05 +00005710 skip = (PyUnicode_Check(name) &&
5711 PyUnicode_GET_SIZE(name) == 9 &&
5712 PyUnicode_CompareWithASCIIString(name, "__class__") == 0);
Guido van Rossum76ba09f2003-04-16 19:40:58 +00005713 }
5714
5715 if (!skip) {
Tim Petersa91e9642001-11-14 23:32:33 +00005716 PyObject *mro, *res, *tmp, *dict;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005717 PyTypeObject *starttype;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005718 descrgetfunc f;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005719 Py_ssize_t i, n;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005720
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005721 starttype = su->obj_type;
Guido van Rossum155db9a2002-04-02 17:53:47 +00005722 mro = starttype->tp_mro;
5723
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005724 if (mro == NULL)
5725 n = 0;
5726 else {
5727 assert(PyTuple_Check(mro));
5728 n = PyTuple_GET_SIZE(mro);
5729 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005730 for (i = 0; i < n; i++) {
Guido van Rossume705ef12001-08-29 15:47:06 +00005731 if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005732 break;
5733 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005734 i++;
5735 res = NULL;
5736 for (; i < n; i++) {
5737 tmp = PyTuple_GET_ITEM(mro, i);
Tim Petersa91e9642001-11-14 23:32:33 +00005738 if (PyType_Check(tmp))
5739 dict = ((PyTypeObject *)tmp)->tp_dict;
Tim Petersa91e9642001-11-14 23:32:33 +00005740 else
5741 continue;
5742 res = PyDict_GetItem(dict, name);
Guido van Rossum6cc5bb62003-04-16 20:01:36 +00005743 if (res != NULL) {
Guido van Rossum705f0f52001-08-24 16:47:00 +00005744 Py_INCREF(res);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005745 f = Py_Type(res)->tp_descr_get;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005746 if (f != NULL) {
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005747 tmp = f(res,
5748 /* Only pass 'obj' param if
5749 this is instance-mode super
5750 (See SF ID #743627)
5751 */
Hye-Shik Changff365c92004-03-25 16:37:03 +00005752 (su->obj == (PyObject *)
5753 su->obj_type
Phillip J. Eby91a968a2004-03-25 02:19:34 +00005754 ? (PyObject *)NULL
5755 : su->obj),
Guido van Rossumd4641072002-04-03 02:13:37 +00005756 (PyObject *)starttype);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005757 Py_DECREF(res);
5758 res = tmp;
5759 }
5760 return res;
5761 }
5762 }
5763 }
5764 return PyObject_GenericGetAttr(self, name);
5765}
5766
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005767static PyTypeObject *
Guido van Rossum5b443c62001-12-03 15:38:28 +00005768supercheck(PyTypeObject *type, PyObject *obj)
5769{
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005770 /* Check that a super() call makes sense. Return a type object.
5771
5772 obj can be a new-style class, or an instance of one:
5773
Guido van Rossumd8faa362007-04-27 19:54:29 +00005774 - If it is a class, it must be a subclass of 'type'. This case is
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005775 used for class methods; the return value is obj.
5776
5777 - If it is an instance, it must be an instance of 'type'. This is
5778 the normal case; the return value is obj.__class__.
5779
5780 But... when obj is an instance, we want to allow for the case where
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005781 Py_Type(obj) is not a subclass of type, but obj.__class__ is!
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005782 This will allow using super() with a proxy for obj.
5783 */
5784
Guido van Rossum8e80a722003-02-18 19:22:22 +00005785 /* Check for first bullet above (special case) */
5786 if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5787 Py_INCREF(obj);
5788 return (PyTypeObject *)obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005789 }
Guido van Rossum8e80a722003-02-18 19:22:22 +00005790
5791 /* Normal case */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005792 if (PyType_IsSubtype(Py_Type(obj), type)) {
5793 Py_INCREF(Py_Type(obj));
5794 return Py_Type(obj);
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005795 }
5796 else {
5797 /* Try the slow way */
5798 static PyObject *class_str = NULL;
5799 PyObject *class_attr;
5800
5801 if (class_str == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00005802 class_str = PyUnicode_FromString("__class__");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005803 if (class_str == NULL)
5804 return NULL;
5805 }
5806
5807 class_attr = PyObject_GetAttr(obj, class_str);
5808
5809 if (class_attr != NULL &&
5810 PyType_Check(class_attr) &&
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005811 (PyTypeObject *)class_attr != Py_Type(obj))
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005812 {
5813 int ok = PyType_IsSubtype(
5814 (PyTypeObject *)class_attr, type);
5815 if (ok)
5816 return (PyTypeObject *)class_attr;
5817 }
5818
5819 if (class_attr == NULL)
5820 PyErr_Clear();
5821 else
5822 Py_DECREF(class_attr);
5823 }
5824
Guido van Rossumd8faa362007-04-27 19:54:29 +00005825 PyErr_SetString(PyExc_TypeError,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005826 "super(type, obj): "
5827 "obj must be an instance or subtype of type");
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005828 return NULL;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005829}
5830
Guido van Rossum705f0f52001-08-24 16:47:00 +00005831static PyObject *
5832super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5833{
5834 superobject *su = (superobject *)self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005835 superobject *newobj;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005836
5837 if (obj == NULL || obj == Py_None || su->obj != NULL) {
5838 /* Not binding to an object, or already bound */
5839 Py_INCREF(self);
5840 return self;
5841 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005842 if (Py_Type(su) != &PySuper_Type)
Armin Rigo7726dc02005-05-15 15:32:08 +00005843 /* If su is an instance of a (strict) subclass of super,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005844 call its type */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005845 return PyObject_CallFunctionObjArgs((PyObject *)Py_Type(su),
Guido van Rossumd8faa362007-04-27 19:54:29 +00005846 su->type, obj, NULL);
Guido van Rossum5b443c62001-12-03 15:38:28 +00005847 else {
5848 /* Inline the common case */
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005849 PyTypeObject *obj_type = supercheck(su->type, obj);
5850 if (obj_type == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005851 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005852 newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
Guido van Rossum5b443c62001-12-03 15:38:28 +00005853 NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005854 if (newobj == NULL)
Guido van Rossum5b443c62001-12-03 15:38:28 +00005855 return NULL;
5856 Py_INCREF(su->type);
5857 Py_INCREF(obj);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005858 newobj->type = su->type;
5859 newobj->obj = obj;
5860 newobj->obj_type = obj_type;
5861 return (PyObject *)newobj;
Guido van Rossum5b443c62001-12-03 15:38:28 +00005862 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005863}
5864
5865static int
5866super_init(PyObject *self, PyObject *args, PyObject *kwds)
5867{
5868 superobject *su = (superobject *)self;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005869 PyTypeObject *type = NULL;
Guido van Rossume705ef12001-08-29 15:47:06 +00005870 PyObject *obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005871 PyTypeObject *obj_type = NULL;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005872
Thomas Wouters89f507f2006-12-13 04:49:30 +00005873 if (!_PyArg_NoKeywords("super", kwds))
5874 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005875 if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
Guido van Rossum705f0f52001-08-24 16:47:00 +00005876 return -1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005877
5878 if (type == NULL) {
5879 /* Call super(), without args -- fill in from __class__
5880 and first local variable on the stack. */
5881 PyFrameObject *f = PyThreadState_GET()->frame;
5882 PyCodeObject *co = f->f_code;
5883 int i, n;
5884 if (co == NULL) {
5885 PyErr_SetString(PyExc_SystemError,
5886 "super(): no code object");
5887 return -1;
5888 }
5889 if (co->co_argcount == 0) {
5890 PyErr_SetString(PyExc_SystemError,
5891 "super(): no arguments");
5892 return -1;
5893 }
5894 obj = f->f_localsplus[0];
5895 if (obj == NULL) {
5896 PyErr_SetString(PyExc_SystemError,
5897 "super(): arg[0] deleted");
5898 return -1;
5899 }
5900 if (co->co_freevars == NULL)
5901 n = 0;
5902 else {
5903 assert(PyTuple_Check(co->co_freevars));
5904 n = PyTuple_GET_SIZE(co->co_freevars);
5905 }
5906 for (i = 0; i < n; i++) {
5907 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
5908 assert(PyUnicode_Check(name));
5909 if (!PyUnicode_CompareWithASCIIString(name,
5910 "__class__")) {
5911 PyObject *cell =
5912 f->f_localsplus[co->co_nlocals + i];
5913 if (cell == NULL || !PyCell_Check(cell)) {
5914 PyErr_SetString(PyExc_SystemError,
5915 "super(): bad __class__ cell");
5916 return -1;
5917 }
5918 type = (PyTypeObject *) PyCell_GET(cell);
5919 if (type == NULL) {
5920 PyErr_SetString(PyExc_SystemError,
5921 "super(): empty __class__ cell");
5922 return -1;
5923 }
5924 if (!PyType_Check(type)) {
5925 PyErr_Format(PyExc_SystemError,
5926 "super(): __class__ is not a type (%s)",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005927 Py_Type(type)->tp_name);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005928 return -1;
5929 }
5930 break;
5931 }
5932 }
5933 if (type == NULL) {
5934 PyErr_SetString(PyExc_SystemError,
5935 "super(): __class__ cell not found");
5936 return -1;
5937 }
5938 }
5939
Guido van Rossum705f0f52001-08-24 16:47:00 +00005940 if (obj == Py_None)
5941 obj = NULL;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005942 if (obj != NULL) {
5943 obj_type = supercheck(type, obj);
5944 if (obj_type == NULL)
5945 return -1;
5946 Py_INCREF(obj);
5947 }
Guido van Rossum705f0f52001-08-24 16:47:00 +00005948 Py_INCREF(type);
Guido van Rossum705f0f52001-08-24 16:47:00 +00005949 su->type = type;
5950 su->obj = obj;
Guido van Rossuma89d10e2003-02-12 03:58:38 +00005951 su->obj_type = obj_type;
Guido van Rossum705f0f52001-08-24 16:47:00 +00005952 return 0;
5953}
5954
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005955PyDoc_STRVAR(super_doc,
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005956"super() -> same as super(__class__, <first argument>)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005957"super(type) -> unbound super object\n"
5958"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
Guido van Rossume705ef12001-08-29 15:47:06 +00005959"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
Guido van Rossum705f0f52001-08-24 16:47:00 +00005960"Typical use to call a cooperative superclass method:\n"
5961"class C(B):\n"
5962" def meth(self, arg):\n"
Guido van Rossumcd16bf62007-06-13 18:07:49 +00005963" super().meth(arg)\n"
5964"This works for class methods too:\n"
5965"class C(B):\n"
5966" @classmethod\n"
5967" def cmeth(cls, arg):\n"
5968" super().cmeth(arg)\n");
Guido van Rossum705f0f52001-08-24 16:47:00 +00005969
Guido van Rossum048eb752001-10-02 21:24:57 +00005970static int
5971super_traverse(PyObject *self, visitproc visit, void *arg)
5972{
5973 superobject *su = (superobject *)self;
Guido van Rossum048eb752001-10-02 21:24:57 +00005974
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005975 Py_VISIT(su->obj);
5976 Py_VISIT(su->type);
5977 Py_VISIT(su->obj_type);
Guido van Rossum048eb752001-10-02 21:24:57 +00005978
5979 return 0;
5980}
5981
Guido van Rossum705f0f52001-08-24 16:47:00 +00005982PyTypeObject PySuper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00005983 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum705f0f52001-08-24 16:47:00 +00005984 "super", /* tp_name */
5985 sizeof(superobject), /* tp_basicsize */
5986 0, /* tp_itemsize */
5987 /* methods */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005988 super_dealloc, /* tp_dealloc */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005989 0, /* tp_print */
5990 0, /* tp_getattr */
5991 0, /* tp_setattr */
5992 0, /* tp_compare */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00005993 super_repr, /* tp_repr */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005994 0, /* tp_as_number */
5995 0, /* tp_as_sequence */
Guido van Rossumd8faa362007-04-27 19:54:29 +00005996 0, /* tp_as_mapping */
Guido van Rossum705f0f52001-08-24 16:47:00 +00005997 0, /* tp_hash */
5998 0, /* tp_call */
5999 0, /* tp_str */
6000 super_getattro, /* tp_getattro */
6001 0, /* tp_setattro */
6002 0, /* tp_as_buffer */
Guido van Rossum048eb752001-10-02 21:24:57 +00006003 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
6004 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006005 super_doc, /* tp_doc */
6006 super_traverse, /* tp_traverse */
6007 0, /* tp_clear */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006008 0, /* tp_richcompare */
6009 0, /* tp_weaklistoffset */
6010 0, /* tp_iter */
6011 0, /* tp_iternext */
6012 0, /* tp_methods */
Guido van Rossum41eb14d2001-08-30 23:13:11 +00006013 super_members, /* tp_members */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006014 0, /* tp_getset */
6015 0, /* tp_base */
6016 0, /* tp_dict */
6017 super_descr_get, /* tp_descr_get */
6018 0, /* tp_descr_set */
6019 0, /* tp_dictoffset */
6020 super_init, /* tp_init */
6021 PyType_GenericAlloc, /* tp_alloc */
6022 PyType_GenericNew, /* tp_new */
Guido van Rossumd8faa362007-04-27 19:54:29 +00006023 PyObject_GC_Del, /* tp_free */
Guido van Rossum705f0f52001-08-24 16:47:00 +00006024};