typeobject.c revision 8e24818cf4919bb7caff7b12a4d7520865c3f0ce
1
2/* Type object implementation */
3
4#include "Python.h"
5#include "structmember.h"
6
7static struct memberlist type_members[] = {
8	{"__name__", T_STRING, offsetof(PyTypeObject, tp_name), READONLY},
9	{"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
10	{"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
11	{"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
12	{"__doc__", T_STRING, offsetof(PyTypeObject, tp_doc), READONLY},
13	{"__weaklistoffset__", T_LONG,
14	 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
15	{"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
16	{"__dictoffset__", T_LONG,
17	 offsetof(PyTypeObject, tp_dictoffset), READONLY},
18	{"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
19	{"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
20	{0}
21};
22
23static PyObject *
24type_module(PyTypeObject *type, void *context)
25{
26	return PyString_FromString("__builtin__");
27}
28
29static PyObject *
30type_dict(PyTypeObject *type, void *context)
31{
32	if (type->tp_dict == NULL) {
33		Py_INCREF(Py_None);
34		return Py_None;
35	}
36 	if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
37		Py_INCREF(type->tp_dict);
38		return type->tp_dict;
39	}
40	return PyDictProxy_New(type->tp_dict);
41}
42
43static PyObject *
44type_defined(PyTypeObject *type, void *context)
45{
46	if (type->tp_defined == NULL) {
47		Py_INCREF(Py_None);
48		return Py_None;
49	}
50	if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
51		Py_INCREF(type->tp_defined);
52		return type->tp_defined;
53	}
54	return PyDictProxy_New(type->tp_defined);
55}
56
57static PyObject *
58type_dynamic(PyTypeObject *type, void *context)
59{
60	PyObject *res;
61
62	res = (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE) ? Py_True : Py_False;
63	Py_INCREF(res);
64	return res;
65}
66
67struct getsetlist type_getsets[] = {
68	{"__module__", (getter)type_module, NULL, NULL},
69	{"__dict__",  (getter)type_dict,  NULL, NULL},
70	{"__defined__",  (getter)type_defined,  NULL, NULL},
71	{"__dynamic__", (getter)type_dynamic, NULL, NULL},
72	{0}
73};
74
75static int
76type_compare(PyObject *v, PyObject *w)
77{
78	/* This is called with type objects only. So we
79	   can just compare the addresses. */
80	Py_uintptr_t vv = (Py_uintptr_t)v;
81	Py_uintptr_t ww = (Py_uintptr_t)w;
82	return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
83}
84
85static PyObject *
86type_repr(PyTypeObject *type)
87{
88	char buf[100];
89	sprintf(buf, "<type '%.80s'>", type->tp_name);
90	return PyString_FromString(buf);
91}
92
93static PyObject *
94type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
95{
96	PyObject *obj;
97
98	if (type->tp_new == NULL) {
99		PyErr_Format(PyExc_TypeError,
100			     "cannot create '%.100s' instances",
101			     type->tp_name);
102		return NULL;
103	}
104
105	obj = type->tp_new(type, args, NULL);
106	if (obj != NULL) {
107		type = obj->ob_type;
108		if (type->tp_init != NULL &&
109		    type->tp_init(obj, args, kwds) < 0) {
110			Py_DECREF(obj);
111			obj = NULL;
112		}
113	}
114	return obj;
115}
116
117PyObject *
118PyType_GenericAlloc(PyTypeObject *type, int nitems)
119{
120	int size;
121	void *mem;
122	PyObject *obj;
123
124	/* Inline PyObject_New() so we can zero the memory */
125	size = _PyObject_VAR_SIZE(type, nitems);
126	mem = PyObject_MALLOC(size);
127	if (mem == NULL)
128		return PyErr_NoMemory();
129	memset(mem, '\0', size);
130	if (PyType_IS_GC(type))
131		obj = PyObject_FROM_GC(mem);
132	else
133		obj = (PyObject *)mem;
134	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
135		Py_INCREF(type);
136	if (type->tp_itemsize == 0)
137		PyObject_INIT(obj, type);
138	else
139		(void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
140	if (PyType_IS_GC(type))
141		PyObject_GC_Init(obj);
142	return obj;
143}
144
145PyObject *
146PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
147{
148	return type->tp_alloc(type, 0);
149}
150
151/* Helper for subtyping */
152
153static void
154subtype_dealloc(PyObject *self)
155{
156	int dictoffset = self->ob_type->tp_dictoffset;
157	PyTypeObject *type, *base;
158	destructor f;
159
160	/* This exists so we can DECREF self->ob_type */
161
162	/* Find the nearest base with a different tp_dealloc */
163	type = self->ob_type;
164	base = type->tp_base;
165	while ((f = base->tp_dealloc) == subtype_dealloc) {
166		base = base->tp_base;
167		assert(base);
168	}
169
170	/* If we added a dict, DECREF it */
171	if (dictoffset && !base->tp_dictoffset) {
172		PyObject **dictptr = (PyObject **) ((char *)self + dictoffset);
173		PyObject *dict = *dictptr;
174		if (dict != NULL) {
175			Py_DECREF(dict);
176			*dictptr = NULL;
177		}
178	}
179
180	/* Finalize GC if the base doesn't do GC and we do */
181	if (PyType_IS_GC(type) && !PyType_IS_GC(base))
182		PyObject_GC_Fini(self);
183
184	/* Call the base tp_dealloc() */
185	assert(f);
186	f(self);
187
188	/* Can't reference self beyond this point */
189	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
190		Py_DECREF(type);
191	}
192}
193
194staticforward void override_slots(PyTypeObject *type, PyObject *dict);
195staticforward PyTypeObject *solid_base(PyTypeObject *type);
196
197typedef struct {
198	PyTypeObject type;
199	PyNumberMethods as_number;
200	PySequenceMethods as_sequence;
201	PyMappingMethods as_mapping;
202	PyBufferProcs as_buffer;
203	PyObject *name, *slots;
204	struct memberlist members[1];
205} etype;
206
207/* type test with subclassing support */
208
209int
210PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
211{
212	PyObject *mro;
213
214	mro = a->tp_mro;
215	if (mro != NULL) {
216		/* Deal with multiple inheritance without recursion
217		   by walking the MRO tuple */
218		int i, n;
219		assert(PyTuple_Check(mro));
220		n = PyTuple_GET_SIZE(mro);
221		for (i = 0; i < n; i++) {
222			if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
223				return 1;
224		}
225		return 0;
226	}
227	else {
228		/* a is not completely initilized yet; follow tp_base */
229		do {
230			if (a == b)
231				return 1;
232			a = a->tp_base;
233		} while (a != NULL);
234		return b == &PyBaseObject_Type;
235	}
236}
237
238/* Method resolution order algorithm from "Putting Metaclasses to Work"
239   by Forman and Danforth (Addison-Wesley 1999). */
240
241static int
242conservative_merge(PyObject *left, PyObject *right)
243{
244	int left_size;
245	int right_size;
246	int i, j, r, ok;
247	PyObject *temp, *rr;
248
249	assert(PyList_Check(left));
250	assert(PyList_Check(right));
251
252  again:
253	left_size = PyList_GET_SIZE(left);
254	right_size = PyList_GET_SIZE(right);
255	for (i = 0; i < left_size; i++) {
256		for (j = 0; j < right_size; j++) {
257			if (PyList_GET_ITEM(left, i) ==
258			    PyList_GET_ITEM(right, j)) {
259				/* found a merge point */
260				temp = PyList_New(0);
261				if (temp == NULL)
262					return -1;
263				for (r = 0; r < j; r++) {
264					rr = PyList_GET_ITEM(right, r);
265					ok = PySequence_Contains(left, rr);
266					if (ok < 0) {
267						Py_DECREF(temp);
268						return -1;
269					}
270					if (!ok) {
271						ok = PyList_Append(temp, rr);
272						if (ok < 0) {
273							Py_DECREF(temp);
274							return -1;
275						}
276					}
277				}
278				ok = PyList_SetSlice(left, i, i, temp);
279				Py_DECREF(temp);
280				if (ok < 0)
281					return -1;
282				ok = PyList_SetSlice(right, 0, j+1, NULL);
283				if (ok < 0)
284					return -1;
285				goto again;
286			}
287		}
288	}
289	return PyList_SetSlice(left, left_size, left_size, right);
290}
291
292static int
293serious_order_disagreements(PyObject *left, PyObject *right)
294{
295	return 0; /* XXX later -- for now, we cheat: "don't do that" */
296}
297
298static PyObject *
299mro_implementation(PyTypeObject *type)
300{
301	int i, n, ok;
302	PyObject *bases, *result;
303
304	bases = type->tp_bases;
305	n = PyTuple_GET_SIZE(bases);
306	result = Py_BuildValue("[O]", (PyObject *)type);
307	if (result == NULL)
308		return NULL;
309	for (i = 0; i < n; i++) {
310		PyTypeObject *base =
311			(PyTypeObject *) PyTuple_GET_ITEM(bases, i);
312		PyObject *parentMRO = PySequence_List(base->tp_mro);
313		if (parentMRO == NULL) {
314			Py_DECREF(result);
315			return NULL;
316		}
317		if (serious_order_disagreements(result, parentMRO)) {
318			Py_DECREF(result);
319			return NULL;
320		}
321		ok = conservative_merge(result, parentMRO);
322		Py_DECREF(parentMRO);
323		if (ok < 0) {
324			Py_DECREF(result);
325			return NULL;
326		}
327	}
328	return result;
329}
330
331static PyObject *
332mro_external(PyObject *self, PyObject *args)
333{
334	PyTypeObject *type = (PyTypeObject *)self;
335
336	if (!PyArg_ParseTuple(args, ""))
337		return NULL;
338	return mro_implementation(type);
339}
340
341static int
342mro_internal(PyTypeObject *type)
343{
344	PyObject *mro, *result, *tuple;
345
346	if (type->ob_type == &PyType_Type) {
347		result = mro_implementation(type);
348	}
349	else {
350		mro = PyObject_GetAttrString((PyObject *)type, "mro");
351		if (mro == NULL)
352			return -1;
353		result = PyObject_CallObject(mro, NULL);
354		Py_DECREF(mro);
355	}
356	if (result == NULL)
357		return -1;
358	tuple = PySequence_Tuple(result);
359	Py_DECREF(result);
360	type->tp_mro = tuple;
361	return 0;
362}
363
364
365/* Calculate the best base amongst multiple base classes.
366   This is the first one that's on the path to the "solid base". */
367
368static PyTypeObject *
369best_base(PyObject *bases)
370{
371	int i, n;
372	PyTypeObject *base, *winner, *candidate, *base_i;
373
374	assert(PyTuple_Check(bases));
375	n = PyTuple_GET_SIZE(bases);
376	assert(n > 0);
377	base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
378	winner = &PyBaseObject_Type;
379	for (i = 0; i < n; i++) {
380		base_i = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
381		if (!PyType_Check((PyObject *)base_i)) {
382			PyErr_SetString(
383				PyExc_TypeError,
384				"bases must be types");
385			return NULL;
386		}
387		if (base_i->tp_dict == NULL) {
388			if (PyType_Ready(base_i) < 0)
389				return NULL;
390		}
391		candidate = solid_base(base_i);
392		if (PyType_IsSubtype(winner, candidate))
393			;
394		else if (PyType_IsSubtype(candidate, winner)) {
395			winner = candidate;
396			base = base_i;
397		}
398		else {
399			PyErr_SetString(
400				PyExc_TypeError,
401				"multiple bases have "
402				"instance lay-out conflict");
403			return NULL;
404		}
405	}
406	assert(base != NULL);
407	return base;
408}
409
410static int
411extra_ivars(PyTypeObject *type, PyTypeObject *base)
412{
413	int t_size = PyType_BASICSIZE(type);
414	int b_size = PyType_BASICSIZE(base);
415
416	assert(t_size >= b_size); /* type smaller than base! */
417	if (type->tp_itemsize || base->tp_itemsize) {
418		/* If itemsize is involved, stricter rules */
419		return t_size != b_size ||
420			type->tp_itemsize != base->tp_itemsize;
421	}
422	if (t_size == b_size)
423		return 0;
424	if (type->tp_dictoffset != 0 && base->tp_dictoffset == 0 &&
425	    type->tp_dictoffset == b_size &&
426	    (size_t)t_size == b_size + sizeof(PyObject *))
427		return 0; /* "Forgive" adding a __dict__ only */
428	return 1;
429}
430
431static PyTypeObject *
432solid_base(PyTypeObject *type)
433{
434	PyTypeObject *base;
435
436	if (type->tp_base)
437		base = solid_base(type->tp_base);
438	else
439		base = &PyBaseObject_Type;
440	if (extra_ivars(type, base))
441		return type;
442	else
443		return base;
444}
445
446staticforward void object_dealloc(PyObject *);
447staticforward int object_init(PyObject *, PyObject *, PyObject *);
448
449static PyObject *
450type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
451{
452	PyObject *name, *bases, *dict;
453	static char *kwlist[] = {"name", "bases", "dict", 0};
454	PyObject *slots, *tmp;
455	PyTypeObject *type, *base, *tmptype;
456	etype *et;
457	struct memberlist *mp;
458	int i, nbases, nslots, slotoffset, dynamic;
459
460	if (metatype == &PyType_Type &&
461	    PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
462	    (kwds == NULL || (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) {
463		/* type(x) -> x.__class__ */
464		PyObject *x = PyTuple_GET_ITEM(args, 0);
465		Py_INCREF(x->ob_type);
466		return (PyObject *) x->ob_type;
467	}
468
469	/* Check arguments */
470	if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
471					 &name,
472					 &PyTuple_Type, &bases,
473					 &PyDict_Type, &dict))
474		return NULL;
475
476	/* Determine the proper metatype to deal with this,
477	   and check for metatype conflicts while we're at it.
478	   Note that if some other metatype wins to contract,
479	   it's possible that its instances are not types. */
480	nbases = PyTuple_GET_SIZE(bases);
481	for (i = 0; i < nbases; i++) {
482		tmp = PyTuple_GET_ITEM(bases, i);
483		tmptype = tmp->ob_type;
484		if (PyType_IsSubtype(metatype, tmptype))
485			continue;
486		if (PyType_IsSubtype(tmptype, metatype)) {
487			metatype = tmptype;
488			continue;
489		}
490		PyErr_SetString(PyExc_TypeError,
491				"metatype conflict among bases");
492		return NULL;
493	}
494	if (metatype->tp_new != type_new) /* Pass it to the winner */
495		return metatype->tp_new(metatype, args, kwds);
496
497	/* Adjust for empty tuple bases */
498	if (nbases == 0) {
499		bases = Py_BuildValue("(O)", &PyBaseObject_Type);
500		if (bases == NULL)
501			return NULL;
502		nbases = 1;
503	}
504	else
505		Py_INCREF(bases);
506
507	/* XXX From here until type is allocated, "return NULL" leaks bases! */
508
509	/* Calculate best base, and check that all bases are type objects */
510	base = best_base(bases);
511	if (base == NULL)
512		return NULL;
513	if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
514		PyErr_Format(PyExc_TypeError,
515			     "type '%.100s' is not an acceptable base type",
516			     base->tp_name);
517		return NULL;
518	}
519
520	/* Should this be a dynamic class (i.e. modifiable __dict__)? */
521	tmp = PyDict_GetItemString(dict, "__dynamic__");
522	if (tmp != NULL) {
523		/* The class author has a preference */
524		dynamic = PyObject_IsTrue(tmp);
525		Py_DECREF(tmp);
526		if (dynamic < 0)
527			return NULL;
528	}
529	else {
530		/* Make a new class dynamic if any of its bases is dynamic.
531		   This is not always the same as inheriting the __dynamic__
532		   class attribute! */
533		dynamic = 0;
534		for (i = 0; i < nbases; i++) {
535			tmptype = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
536			if (tmptype->tp_flags & Py_TPFLAGS_DYNAMICTYPE) {
537				dynamic = 1;
538				break;
539			}
540		}
541	}
542
543	/* Check for a __slots__ sequence variable in dict, and count it */
544	slots = PyDict_GetItemString(dict, "__slots__");
545	nslots = 0;
546	if (slots != NULL) {
547		/* Make it into a tuple */
548		if (PyString_Check(slots))
549			slots = Py_BuildValue("(O)", slots);
550		else
551			slots = PySequence_Tuple(slots);
552		if (slots == NULL)
553			return NULL;
554		nslots = PyTuple_GET_SIZE(slots);
555		for (i = 0; i < nslots; i++) {
556			if (!PyString_Check(PyTuple_GET_ITEM(slots, i))) {
557				PyErr_SetString(PyExc_TypeError,
558				"__slots__ must be a sequence of strings");
559				Py_DECREF(slots);
560				return NULL;
561			}
562		}
563	}
564	if (slots == NULL && base->tp_dictoffset == 0 &&
565	    (base->tp_setattro == PyObject_GenericSetAttr ||
566	     base->tp_setattro == NULL))
567		nslots = 1;
568
569	/* XXX From here until type is safely allocated,
570	   "return NULL" may leak slots! */
571
572	/* Allocate the type object */
573	type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
574	if (type == NULL)
575		return NULL;
576
577	/* Keep name and slots alive in the extended type object */
578	et = (etype *)type;
579	Py_INCREF(name);
580	et->name = name;
581	et->slots = slots;
582
583	/* Initialize tp_flags */
584	type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
585		Py_TPFLAGS_BASETYPE;
586	if (dynamic)
587		type->tp_flags |= Py_TPFLAGS_DYNAMICTYPE;
588
589	/* It's a new-style number unless it specifically inherits any
590	   old-style numeric behavior */
591	if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
592	    (base->tp_as_number == NULL))
593		type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
594
595	/* Initialize essential fields */
596	type->tp_as_number = &et->as_number;
597	type->tp_as_sequence = &et->as_sequence;
598	type->tp_as_mapping = &et->as_mapping;
599	type->tp_as_buffer = &et->as_buffer;
600	type->tp_name = PyString_AS_STRING(name);
601
602	/* Set tp_base and tp_bases */
603	type->tp_bases = bases;
604	Py_INCREF(base);
605	type->tp_base = base;
606
607	/* Initialize tp_defined from passed-in dict */
608	type->tp_defined = dict = PyDict_Copy(dict);
609	if (dict == NULL) {
610		Py_DECREF(type);
611		return NULL;
612	}
613
614	/* Special-case __new__: if it's a plain function,
615	   make it a static function */
616	tmp = PyDict_GetItemString(dict, "__new__");
617	if (tmp != NULL && PyFunction_Check(tmp)) {
618		tmp = PyStaticMethod_New(tmp);
619		if (tmp == NULL) {
620			Py_DECREF(type);
621			return NULL;
622		}
623		PyDict_SetItemString(dict, "__new__", tmp);
624		Py_DECREF(tmp);
625	}
626
627	/* Add descriptors for custom slots from __slots__, or for __dict__ */
628	mp = et->members;
629	slotoffset = PyType_BASICSIZE(base);
630	if (slots != NULL) {
631		for (i = 0; i < nslots; i++, mp++) {
632			mp->name = PyString_AS_STRING(
633				PyTuple_GET_ITEM(slots, i));
634			mp->type = T_OBJECT;
635			mp->offset = slotoffset;
636			slotoffset += sizeof(PyObject *);
637		}
638	}
639	else if (nslots) {
640		type->tp_dictoffset = slotoffset;
641		mp->name = "__dict__";
642		mp->type = T_OBJECT;
643		mp->offset = slotoffset;
644		mp->readonly = 1;
645		slotoffset += sizeof(PyObject *);
646	}
647	type->tp_basicsize = slotoffset;
648	type->tp_members = et->members;
649
650	/* Special case some slots */
651	if (type->tp_dictoffset != 0 || nslots > 0) {
652		if (base->tp_getattr == NULL && base->tp_getattro == NULL)
653			type->tp_getattro = PyObject_GenericGetAttr;
654		if (base->tp_setattr == NULL && base->tp_setattro == NULL)
655			type->tp_setattro = PyObject_GenericSetAttr;
656	}
657	type->tp_dealloc = subtype_dealloc;
658
659	/* Always override allocation strategy to use regular heap */
660	type->tp_alloc = PyType_GenericAlloc;
661	type->tp_free = _PyObject_Del;
662
663	/* Initialize the rest */
664	if (PyType_Ready(type) < 0) {
665		Py_DECREF(type);
666		return NULL;
667	}
668
669	/* Override slots that deserve it */
670	if (!PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE))
671		override_slots(type, type->tp_defined);
672
673	return (PyObject *)type;
674}
675
676/* Internal API to look for a name through the MRO.
677   This returns a borrowed reference, and doesn't set an exception! */
678PyObject *
679_PyType_Lookup(PyTypeObject *type, PyObject *name)
680{
681	int i, n;
682	PyObject *mro, *res, *dict;
683
684	/* For static types, look in tp_dict */
685	if (!(type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)) {
686		dict = type->tp_dict;
687		assert(dict && PyDict_Check(dict));
688		return PyDict_GetItem(dict, name);
689	}
690
691	/* For dynamic types, look in tp_defined of types in MRO */
692	mro = type->tp_mro;
693	assert(PyTuple_Check(mro));
694	n = PyTuple_GET_SIZE(mro);
695	for (i = 0; i < n; i++) {
696		type = (PyTypeObject *) PyTuple_GET_ITEM(mro, i);
697		assert(PyType_Check(type));
698		dict = type->tp_defined;
699		assert(dict && PyDict_Check(dict));
700		res = PyDict_GetItem(dict, name);
701		if (res != NULL)
702			return res;
703	}
704	return NULL;
705}
706
707/* This is similar to PyObject_GenericGetAttr(),
708   but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
709static PyObject *
710type_getattro(PyTypeObject *type, PyObject *name)
711{
712	PyTypeObject *metatype = type->ob_type;
713	PyObject *descr, *res;
714	descrgetfunc f;
715
716	/* Initialize this type (we'll assume the metatype is initialized) */
717	if (type->tp_dict == NULL) {
718		if (PyType_Ready(type) < 0)
719			return NULL;
720	}
721
722	/* Get a descriptor from the metatype */
723	descr = _PyType_Lookup(metatype, name);
724	f = NULL;
725	if (descr != NULL) {
726		f = descr->ob_type->tp_descr_get;
727		if (f != NULL && PyDescr_IsData(descr))
728			return f(descr,
729				 (PyObject *)type, (PyObject *)metatype);
730	}
731
732	/* Look in tp_defined of this type and its bases */
733	res = _PyType_Lookup(type, name);
734	if (res != NULL) {
735		f = res->ob_type->tp_descr_get;
736		if (f != NULL)
737			return f(res, (PyObject *)NULL, (PyObject *)type);
738		Py_INCREF(res);
739		return res;
740	}
741
742	/* Use the descriptor from the metatype */
743	if (f != NULL) {
744		res = f(descr, (PyObject *)type, (PyObject *)metatype);
745		return res;
746	}
747	if (descr != NULL) {
748		Py_INCREF(descr);
749		return descr;
750	}
751
752	/* Give up */
753	PyErr_Format(PyExc_AttributeError,
754		     "type object '%.50s' has no attribute '%.400s'",
755		     type->tp_name, PyString_AS_STRING(name));
756	return NULL;
757}
758
759static int
760type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
761{
762	if (type->tp_flags & Py_TPFLAGS_DYNAMICTYPE)
763		return PyObject_GenericSetAttr((PyObject *)type, name, value);
764	PyErr_SetString(PyExc_TypeError, "can't set type attributes");
765	return -1;
766}
767
768static void
769type_dealloc(PyTypeObject *type)
770{
771	etype *et;
772
773	/* Assert this is a heap-allocated type object */
774	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
775	et = (etype *)type;
776	Py_XDECREF(type->tp_base);
777	Py_XDECREF(type->tp_dict);
778	Py_XDECREF(type->tp_bases);
779	Py_XDECREF(type->tp_mro);
780	Py_XDECREF(type->tp_defined);
781	/* XXX more? */
782	Py_XDECREF(et->name);
783	Py_XDECREF(et->slots);
784	type->ob_type->tp_free((PyObject *)type);
785}
786
787static PyMethodDef type_methods[] = {
788	{"mro", mro_external, METH_VARARGS,
789	 "mro() -> list\nreturn a type's method resolution order"},
790	{0}
791};
792
793static char type_doc[] =
794"type(object) -> the object's type\n"
795"type(name, bases, dict) -> a new type";
796
797PyTypeObject PyType_Type = {
798	PyObject_HEAD_INIT(&PyType_Type)
799	0,					/* ob_size */
800	"type",					/* tp_name */
801	sizeof(etype),				/* tp_basicsize */
802	sizeof(struct memberlist),		/* tp_itemsize */
803	(destructor)type_dealloc,		/* tp_dealloc */
804	0,					/* tp_print */
805	0,			 		/* tp_getattr */
806	0,					/* tp_setattr */
807	type_compare,				/* tp_compare */
808	(reprfunc)type_repr,			/* tp_repr */
809	0,					/* tp_as_number */
810	0,					/* tp_as_sequence */
811	0,					/* tp_as_mapping */
812	(hashfunc)_Py_HashPointer,		/* tp_hash */
813	(ternaryfunc)type_call,			/* tp_call */
814	0,					/* tp_str */
815	(getattrofunc)type_getattro,		/* tp_getattro */
816	(setattrofunc)type_setattro,		/* tp_setattro */
817	0,					/* tp_as_buffer */
818	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
819	type_doc,				/* tp_doc */
820	0,					/* tp_traverse */
821	0,					/* tp_clear */
822	0,					/* tp_richcompare */
823	0,					/* tp_weaklistoffset */
824	0,					/* tp_iter */
825	0,					/* tp_iternext */
826	type_methods,				/* tp_methods */
827	type_members,				/* tp_members */
828	type_getsets,				/* tp_getset */
829	0,					/* tp_base */
830	0,					/* tp_dict */
831	0,					/* tp_descr_get */
832	0,					/* tp_descr_set */
833	offsetof(PyTypeObject, tp_dict),	/* tp_dictoffset */
834	0,					/* tp_init */
835	0,					/* tp_alloc */
836	type_new,				/* tp_new */
837};
838
839
840/* The base type of all types (eventually)... except itself. */
841
842static int
843object_init(PyObject *self, PyObject *args, PyObject *kwds)
844{
845	return 0;
846}
847
848static void
849object_dealloc(PyObject *self)
850{
851	self->ob_type->tp_free(self);
852}
853
854#if 0
855static PyObject *
856object_repr(PyObject *self)
857{
858	char buf[120];
859
860	sprintf(buf, "<%.80s object at %p>", self->ob_type->tp_name, self);
861	return PyString_FromString(buf);
862}
863
864static long
865object_hash(PyObject *self)
866{
867	return _Py_HashPointer(self);
868}
869#endif
870
871static void
872object_free(PyObject *self)
873{
874	PyObject_Del(self);
875}
876
877static struct memberlist object_members[] = {
878	{"__class__", T_OBJECT, offsetof(PyObject, ob_type), READONLY},
879	{0}
880};
881
882PyTypeObject PyBaseObject_Type = {
883	PyObject_HEAD_INIT(&PyType_Type)
884 	0,					/* ob_size */
885	"object",				/* tp_name */
886	sizeof(PyObject),			/* tp_basicsize */
887	0,					/* tp_itemsize */
888	(destructor)object_dealloc,		/* tp_dealloc */
889	0,					/* tp_print */
890	0,			 		/* tp_getattr */
891	0,					/* tp_setattr */
892	0,					/* tp_compare */
893	0,					/* tp_repr */
894	0,					/* tp_as_number */
895	0,					/* tp_as_sequence */
896	0,					/* tp_as_mapping */
897	0,					/* tp_hash */
898	0,					/* tp_call */
899	0,					/* tp_str */
900	PyObject_GenericGetAttr,		/* tp_getattro */
901	PyObject_GenericSetAttr,		/* tp_setattro */
902	0,					/* tp_as_buffer */
903	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
904	"The most base type",			/* tp_doc */
905	0,					/* tp_traverse */
906	0,					/* tp_clear */
907	0,					/* tp_richcompare */
908	0,					/* tp_weaklistoffset */
909	0,					/* tp_iter */
910	0,					/* tp_iternext */
911	0,					/* tp_methods */
912	object_members,				/* tp_members */
913	0,					/* tp_getset */
914	0,					/* tp_base */
915	0,					/* tp_dict */
916	0,					/* tp_descr_get */
917	0,					/* tp_descr_set */
918	0,					/* tp_dictoffset */
919	object_init,				/* tp_init */
920	PyType_GenericAlloc,			/* tp_alloc */
921	PyType_GenericNew,			/* tp_new */
922	object_free,				/* tp_free */
923};
924
925
926/* Initialize the __dict__ in a type object */
927
928static int
929add_methods(PyTypeObject *type, PyMethodDef *meth)
930{
931	PyObject *dict = type->tp_defined;
932
933	for (; meth->ml_name != NULL; meth++) {
934		PyObject *descr;
935		if (PyDict_GetItemString(dict, meth->ml_name))
936			continue;
937		descr = PyDescr_NewMethod(type, meth);
938		if (descr == NULL)
939			return -1;
940		if (PyDict_SetItemString(dict,meth->ml_name,descr) < 0)
941			return -1;
942		Py_DECREF(descr);
943	}
944	return 0;
945}
946
947static int
948add_members(PyTypeObject *type, struct memberlist *memb)
949{
950	PyObject *dict = type->tp_defined;
951
952	for (; memb->name != NULL; memb++) {
953		PyObject *descr;
954		if (PyDict_GetItemString(dict, memb->name))
955			continue;
956		descr = PyDescr_NewMember(type, memb);
957		if (descr == NULL)
958			return -1;
959		if (PyDict_SetItemString(dict, memb->name, descr) < 0)
960			return -1;
961		Py_DECREF(descr);
962	}
963	return 0;
964}
965
966static int
967add_getset(PyTypeObject *type, struct getsetlist *gsp)
968{
969	PyObject *dict = type->tp_defined;
970
971	for (; gsp->name != NULL; gsp++) {
972		PyObject *descr;
973		if (PyDict_GetItemString(dict, gsp->name))
974			continue;
975		descr = PyDescr_NewGetSet(type, gsp);
976
977		if (descr == NULL)
978			return -1;
979		if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
980			return -1;
981		Py_DECREF(descr);
982	}
983	return 0;
984}
985
986static void
987inherit_special(PyTypeObject *type, PyTypeObject *base)
988{
989	int oldsize, newsize;
990
991	/* Special flag magic */
992	if (!type->tp_as_buffer && base->tp_as_buffer) {
993		type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
994		type->tp_flags |=
995			base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
996	}
997	if (!type->tp_as_sequence && base->tp_as_sequence) {
998		type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
999		type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
1000	}
1001	if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
1002	    (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
1003		if ((!type->tp_as_number && base->tp_as_number) ||
1004		    (!type->tp_as_sequence && base->tp_as_sequence)) {
1005			type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
1006			if (!type->tp_as_number && !type->tp_as_sequence) {
1007				type->tp_flags |= base->tp_flags &
1008					Py_TPFLAGS_HAVE_INPLACEOPS;
1009			}
1010		}
1011		/* Wow */
1012	}
1013	if (!type->tp_as_number && base->tp_as_number) {
1014		type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
1015		type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
1016	}
1017
1018	/* Copying basicsize is connected to the GC flags */
1019	oldsize = PyType_BASICSIZE(base);
1020	newsize = type->tp_basicsize ? PyType_BASICSIZE(type) : oldsize;
1021	if (!(type->tp_flags & Py_TPFLAGS_GC) &&
1022	    (base->tp_flags & Py_TPFLAGS_GC) &&
1023	    (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
1024	    (!type->tp_traverse && !type->tp_clear)) {
1025		type->tp_flags |= Py_TPFLAGS_GC;
1026		if (type->tp_traverse == NULL)
1027			type->tp_traverse = base->tp_traverse;
1028		if (type->tp_clear == NULL)
1029			type->tp_clear = base->tp_clear;
1030	}
1031	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1032		if (base != &PyBaseObject_Type ||
1033		    (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
1034			if (type->tp_new == NULL)
1035				type->tp_new = base->tp_new;
1036		}
1037	}
1038	PyType_SET_BASICSIZE(type, newsize);
1039}
1040
1041static void
1042inherit_slots(PyTypeObject *type, PyTypeObject *base)
1043{
1044	PyTypeObject *basebase;
1045
1046#undef SLOTDEFINED
1047#undef COPYSLOT
1048#undef COPYNUM
1049#undef COPYSEQ
1050#undef COPYMAP
1051
1052#define SLOTDEFINED(SLOT) \
1053	(base->SLOT != 0 && \
1054	 (basebase == NULL || base->SLOT != basebase->SLOT))
1055
1056#define COPYSLOT(SLOT) \
1057	if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
1058
1059#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
1060#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
1061#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
1062
1063	/* This won't inherit indirect slots (from tp_as_number etc.)
1064	   if type doesn't provide the space. */
1065
1066	if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
1067		basebase = base->tp_base;
1068		if (basebase->tp_as_number == NULL)
1069			basebase = NULL;
1070		COPYNUM(nb_add);
1071		COPYNUM(nb_subtract);
1072		COPYNUM(nb_multiply);
1073		COPYNUM(nb_divide);
1074		COPYNUM(nb_remainder);
1075		COPYNUM(nb_divmod);
1076		COPYNUM(nb_power);
1077		COPYNUM(nb_negative);
1078		COPYNUM(nb_positive);
1079		COPYNUM(nb_absolute);
1080		COPYNUM(nb_nonzero);
1081		COPYNUM(nb_invert);
1082		COPYNUM(nb_lshift);
1083		COPYNUM(nb_rshift);
1084		COPYNUM(nb_and);
1085		COPYNUM(nb_xor);
1086		COPYNUM(nb_or);
1087		COPYNUM(nb_coerce);
1088		COPYNUM(nb_int);
1089		COPYNUM(nb_long);
1090		COPYNUM(nb_float);
1091		COPYNUM(nb_oct);
1092		COPYNUM(nb_hex);
1093		COPYNUM(nb_inplace_add);
1094		COPYNUM(nb_inplace_subtract);
1095		COPYNUM(nb_inplace_multiply);
1096		COPYNUM(nb_inplace_divide);
1097		COPYNUM(nb_inplace_remainder);
1098		COPYNUM(nb_inplace_power);
1099		COPYNUM(nb_inplace_lshift);
1100		COPYNUM(nb_inplace_rshift);
1101		COPYNUM(nb_inplace_and);
1102		COPYNUM(nb_inplace_xor);
1103		COPYNUM(nb_inplace_or);
1104		if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
1105			COPYNUM(nb_true_divide);
1106			COPYNUM(nb_floor_divide);
1107			COPYNUM(nb_inplace_true_divide);
1108			COPYNUM(nb_inplace_floor_divide);
1109		}
1110	}
1111
1112	if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
1113		basebase = base->tp_base;
1114		if (basebase->tp_as_sequence == NULL)
1115			basebase = NULL;
1116		COPYSEQ(sq_length);
1117		COPYSEQ(sq_concat);
1118		COPYSEQ(sq_repeat);
1119		COPYSEQ(sq_item);
1120		COPYSEQ(sq_slice);
1121		COPYSEQ(sq_ass_item);
1122		COPYSEQ(sq_ass_slice);
1123		COPYSEQ(sq_contains);
1124		COPYSEQ(sq_inplace_concat);
1125		COPYSEQ(sq_inplace_repeat);
1126	}
1127
1128	if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
1129		basebase = base->tp_base;
1130		if (basebase->tp_as_mapping == NULL)
1131			basebase = NULL;
1132		COPYMAP(mp_length);
1133		COPYMAP(mp_subscript);
1134		COPYMAP(mp_ass_subscript);
1135	}
1136
1137	basebase = base->tp_base;
1138
1139	COPYSLOT(tp_itemsize);
1140	COPYSLOT(tp_dealloc);
1141	COPYSLOT(tp_print);
1142	if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
1143		type->tp_getattr = base->tp_getattr;
1144		type->tp_getattro = base->tp_getattro;
1145	}
1146	if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
1147		type->tp_setattr = base->tp_setattr;
1148		type->tp_setattro = base->tp_setattro;
1149	}
1150	/* tp_compare see tp_richcompare */
1151	COPYSLOT(tp_repr);
1152	COPYSLOT(tp_hash);
1153	COPYSLOT(tp_call);
1154	COPYSLOT(tp_str);
1155	COPYSLOT(tp_as_buffer);
1156	COPYSLOT(tp_flags);
1157	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
1158		if (type->tp_compare == NULL && type->tp_richcompare == NULL) {
1159			type->tp_compare = base->tp_compare;
1160			type->tp_richcompare = base->tp_richcompare;
1161		}
1162	}
1163	else {
1164		COPYSLOT(tp_compare);
1165	}
1166	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
1167		COPYSLOT(tp_weaklistoffset);
1168	}
1169	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
1170		COPYSLOT(tp_iter);
1171		COPYSLOT(tp_iternext);
1172	}
1173	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
1174		COPYSLOT(tp_descr_get);
1175		COPYSLOT(tp_descr_set);
1176		COPYSLOT(tp_dictoffset);
1177		COPYSLOT(tp_init);
1178		COPYSLOT(tp_alloc);
1179		COPYSLOT(tp_free);
1180	}
1181}
1182
1183staticforward int add_operators(PyTypeObject *);
1184
1185int
1186PyType_Ready(PyTypeObject *type)
1187{
1188	PyObject *dict, *bases, *x;
1189	PyTypeObject *base;
1190	int i, n;
1191
1192	if (type->tp_flags & Py_TPFLAGS_READY) {
1193		assert(type->tp_dict != NULL);
1194		return 0;
1195	}
1196	assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
1197	assert(type->tp_dict == NULL);
1198
1199	type->tp_flags |= Py_TPFLAGS_READYING;
1200
1201	/* Initialize tp_base (defaults to BaseObject unless that's us) */
1202	base = type->tp_base;
1203	if (base == NULL && type != &PyBaseObject_Type)
1204		base = type->tp_base = &PyBaseObject_Type;
1205
1206	/* Initialize tp_bases */
1207	bases = type->tp_bases;
1208	if (bases == NULL) {
1209		if (base == NULL)
1210			bases = PyTuple_New(0);
1211		else
1212			bases = Py_BuildValue("(O)", base);
1213		if (bases == NULL)
1214			goto error;
1215		type->tp_bases = bases;
1216	}
1217
1218	/* Initialize the base class */
1219	if (base && base->tp_dict == NULL) {
1220		if (PyType_Ready(base) < 0)
1221			goto error;
1222	}
1223
1224	/* Initialize tp_defined */
1225	dict = type->tp_defined;
1226	if (dict == NULL) {
1227		dict = PyDict_New();
1228		if (dict == NULL)
1229			goto error;
1230		type->tp_defined = dict;
1231	}
1232
1233	/* Add type-specific descriptors to tp_defined */
1234	if (add_operators(type) < 0)
1235		goto error;
1236	if (type->tp_methods != NULL) {
1237		if (add_methods(type, type->tp_methods) < 0)
1238			goto error;
1239	}
1240	if (type->tp_members != NULL) {
1241		if (add_members(type, type->tp_members) < 0)
1242			goto error;
1243	}
1244	if (type->tp_getset != NULL) {
1245		if (add_getset(type, type->tp_getset) < 0)
1246			goto error;
1247	}
1248
1249	/* Temporarily make tp_dict the same object as tp_defined.
1250	   (This is needed to call mro(), and can stay this way for
1251	   dynamic types). */
1252	Py_INCREF(type->tp_defined);
1253	type->tp_dict = type->tp_defined;
1254
1255	/* Calculate method resolution order */
1256	if (mro_internal(type) < 0) {
1257		goto error;
1258	}
1259
1260	/* Inherit special flags from dominant base */
1261	if (type->tp_base != NULL)
1262		inherit_special(type, type->tp_base);
1263
1264	/* Initialize tp_dict properly */
1265	if (PyType_HasFeature(type, Py_TPFLAGS_DYNAMICTYPE)) {
1266		/* For a dynamic type, all slots are overridden */
1267		override_slots(type, NULL);
1268	}
1269	else {
1270		/* For a static type, tp_dict is the consolidation
1271		   of the tp_defined of its bases in MRO. */
1272		Py_DECREF(type->tp_dict);
1273		type->tp_dict = PyDict_Copy(type->tp_defined);
1274		if (type->tp_dict == NULL)
1275			goto error;
1276		bases = type->tp_mro;
1277		assert(bases != NULL);
1278		assert(PyTuple_Check(bases));
1279		n = PyTuple_GET_SIZE(bases);
1280		for (i = 1; i < n; i++) {
1281			base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i);
1282			assert(PyType_Check(base));
1283			x = base->tp_defined;
1284			if (x != NULL && PyDict_Merge(type->tp_dict, x, 0) < 0)
1285				goto error;
1286			inherit_slots(type, base);
1287		}
1288	}
1289
1290	/* Some more special stuff */
1291	base = type->tp_base;
1292	if (base != NULL) {
1293		if (type->tp_as_number == NULL)
1294			type->tp_as_number = base->tp_as_number;
1295		if (type->tp_as_sequence == NULL)
1296			type->tp_as_sequence = base->tp_as_sequence;
1297		if (type->tp_as_mapping == NULL)
1298			type->tp_as_mapping = base->tp_as_mapping;
1299	}
1300
1301	/* All done -- set the ready flag */
1302	assert(type->tp_dict != NULL);
1303	type->tp_flags =
1304		(type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
1305	return 0;
1306
1307  error:
1308	type->tp_flags &= ~Py_TPFLAGS_READYING;
1309	return -1;
1310}
1311
1312
1313/* Generic wrappers for overloadable 'operators' such as __getitem__ */
1314
1315/* There's a wrapper *function* for each distinct function typedef used
1316   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
1317   wrapper *table* for each distinct operation (e.g. __len__, __add__).
1318   Most tables have only one entry; the tables for binary operators have two
1319   entries, one regular and one with reversed arguments. */
1320
1321static PyObject *
1322wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
1323{
1324	inquiry func = (inquiry)wrapped;
1325	int res;
1326
1327	if (!PyArg_ParseTuple(args, ""))
1328		return NULL;
1329	res = (*func)(self);
1330	if (res == -1 && PyErr_Occurred())
1331		return NULL;
1332	return PyInt_FromLong((long)res);
1333}
1334
1335static struct wrapperbase tab_len[] = {
1336	{"__len__", (wrapperfunc)wrap_inquiry, "x.__len__() <==> len(x)"},
1337	{0}
1338};
1339
1340static PyObject *
1341wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
1342{
1343	binaryfunc func = (binaryfunc)wrapped;
1344	PyObject *other;
1345
1346	if (!PyArg_ParseTuple(args, "O", &other))
1347		return NULL;
1348	return (*func)(self, other);
1349}
1350
1351static PyObject *
1352wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
1353{
1354	binaryfunc func = (binaryfunc)wrapped;
1355	PyObject *other;
1356
1357	if (!PyArg_ParseTuple(args, "O", &other))
1358		return NULL;
1359	return (*func)(other, self);
1360}
1361
1362#undef BINARY
1363#define BINARY(NAME, OP) \
1364static struct wrapperbase tab_##NAME[] = { \
1365	{"__" #NAME "__", \
1366	 (wrapperfunc)wrap_binaryfunc, \
1367	 "x.__" #NAME "__(y) <==> " #OP}, \
1368	{"__r" #NAME "__", \
1369	 (wrapperfunc)wrap_binaryfunc_r, \
1370	 "y.__r" #NAME "__(x) <==> " #OP}, \
1371	{0} \
1372}
1373
1374BINARY(add, "x+y");
1375BINARY(sub, "x-y");
1376BINARY(mul, "x*y");
1377BINARY(div, "x/y");
1378BINARY(mod, "x%y");
1379BINARY(divmod, "divmod(x,y)");
1380BINARY(lshift, "x<<y");
1381BINARY(rshift, "x>>y");
1382BINARY(and, "x&y");
1383BINARY(xor, "x^y");
1384BINARY(or, "x|y");
1385
1386static PyObject *
1387wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
1388{
1389	ternaryfunc func = (ternaryfunc)wrapped;
1390	PyObject *other;
1391	PyObject *third = Py_None;
1392
1393	/* Note: This wrapper only works for __pow__() */
1394
1395	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
1396		return NULL;
1397	return (*func)(self, other, third);
1398}
1399
1400#undef TERNARY
1401#define TERNARY(NAME, OP) \
1402static struct wrapperbase tab_##NAME[] = { \
1403	{"__" #NAME "__", \
1404	 (wrapperfunc)wrap_ternaryfunc, \
1405	 "x.__" #NAME "__(y, z) <==> " #OP}, \
1406	{"__r" #NAME "__", \
1407	 (wrapperfunc)wrap_ternaryfunc, \
1408	 "y.__r" #NAME "__(x, z) <==> " #OP}, \
1409	{0} \
1410}
1411
1412TERNARY(pow, "(x**y) % z");
1413
1414#undef UNARY
1415#define UNARY(NAME, OP) \
1416static struct wrapperbase tab_##NAME[] = { \
1417	{"__" #NAME "__", \
1418	 (wrapperfunc)wrap_unaryfunc, \
1419	 "x.__" #NAME "__() <==> " #OP}, \
1420	{0} \
1421}
1422
1423static PyObject *
1424wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
1425{
1426	unaryfunc func = (unaryfunc)wrapped;
1427
1428	if (!PyArg_ParseTuple(args, ""))
1429		return NULL;
1430	return (*func)(self);
1431}
1432
1433UNARY(neg, "-x");
1434UNARY(pos, "+x");
1435UNARY(abs, "abs(x)");
1436UNARY(nonzero, "x != 0");
1437UNARY(invert, "~x");
1438UNARY(int, "int(x)");
1439UNARY(long, "long(x)");
1440UNARY(float, "float(x)");
1441UNARY(oct, "oct(x)");
1442UNARY(hex, "hex(x)");
1443
1444#undef IBINARY
1445#define IBINARY(NAME, OP) \
1446static struct wrapperbase tab_##NAME[] = { \
1447	{"__" #NAME "__", \
1448	 (wrapperfunc)wrap_binaryfunc, \
1449	 "x.__" #NAME "__(y) <==> " #OP}, \
1450	{0} \
1451}
1452
1453IBINARY(iadd, "x+=y");
1454IBINARY(isub, "x-=y");
1455IBINARY(imul, "x*=y");
1456IBINARY(idiv, "x/=y");
1457IBINARY(imod, "x%=y");
1458IBINARY(ilshift, "x<<=y");
1459IBINARY(irshift, "x>>=y");
1460IBINARY(iand, "x&=y");
1461IBINARY(ixor, "x^=y");
1462IBINARY(ior, "x|=y");
1463
1464#undef ITERNARY
1465#define ITERNARY(NAME, OP) \
1466static struct wrapperbase tab_##NAME[] = { \
1467	{"__" #NAME "__", \
1468	 (wrapperfunc)wrap_ternaryfunc, \
1469	 "x.__" #NAME "__(y) <==> " #OP}, \
1470	{0} \
1471}
1472
1473ITERNARY(ipow, "x = (x**y) % z");
1474
1475static struct wrapperbase tab_getitem[] = {
1476	{"__getitem__", (wrapperfunc)wrap_binaryfunc,
1477	 "x.__getitem__(y) <==> x[y]"},
1478	{0}
1479};
1480
1481static PyObject *
1482wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
1483{
1484	intargfunc func = (intargfunc)wrapped;
1485	int i;
1486
1487	if (!PyArg_ParseTuple(args, "i", &i))
1488		return NULL;
1489	return (*func)(self, i);
1490}
1491
1492static struct wrapperbase tab_mul_int[] = {
1493	{"__mul__", (wrapperfunc)wrap_intargfunc, "x.__mul__(n) <==> x*n"},
1494	{"__rmul__", (wrapperfunc)wrap_intargfunc, "x.__rmul__(n) <==> n*x"},
1495	{0}
1496};
1497
1498static struct wrapperbase tab_concat[] = {
1499	{"__add__", (wrapperfunc)wrap_binaryfunc, "x.__add__(y) <==> x+y"},
1500	{0}
1501};
1502
1503static struct wrapperbase tab_imul_int[] = {
1504	{"__imul__", (wrapperfunc)wrap_intargfunc, "x.__imul__(n) <==> x*=n"},
1505	{0}
1506};
1507
1508static struct wrapperbase tab_getitem_int[] = {
1509	{"__getitem__", (wrapperfunc)wrap_intargfunc,
1510	 "x.__getitem__(i) <==> x[i]"},
1511	{0}
1512};
1513
1514static PyObject *
1515wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
1516{
1517	intintargfunc func = (intintargfunc)wrapped;
1518	int i, j;
1519
1520	if (!PyArg_ParseTuple(args, "ii", &i, &j))
1521		return NULL;
1522	return (*func)(self, i, j);
1523}
1524
1525static struct wrapperbase tab_getslice[] = {
1526	{"__getslice__", (wrapperfunc)wrap_intintargfunc,
1527	 "x.__getslice__(i, j) <==> x[i:j]"},
1528	{0}
1529};
1530
1531static PyObject *
1532wrap_intobjargproc(PyObject *self, PyObject *args, void *wrapped)
1533{
1534	intobjargproc func = (intobjargproc)wrapped;
1535	int i, res;
1536	PyObject *value;
1537
1538	if (!PyArg_ParseTuple(args, "iO", &i, &value))
1539		return NULL;
1540	res = (*func)(self, i, value);
1541	if (res == -1 && PyErr_Occurred())
1542		return NULL;
1543	Py_INCREF(Py_None);
1544	return Py_None;
1545}
1546
1547static PyObject *
1548wrap_delitem_int(PyObject *self, PyObject *args, void *wrapped)
1549{
1550	intobjargproc func = (intobjargproc)wrapped;
1551	int i, res;
1552
1553	if (!PyArg_ParseTuple(args, "i", &i))
1554		return NULL;
1555	res = (*func)(self, i, NULL);
1556	if (res == -1 && PyErr_Occurred())
1557		return NULL;
1558	Py_INCREF(Py_None);
1559	return Py_None;
1560}
1561
1562static struct wrapperbase tab_setitem_int[] = {
1563	{"__setitem__", (wrapperfunc)wrap_intobjargproc,
1564	 "x.__setitem__(i, y) <==> x[i]=y"},
1565	{"__delitem__", (wrapperfunc)wrap_delitem_int,
1566	 "x.__delitem__(y) <==> del x[y]"},
1567	{0}
1568};
1569
1570static PyObject *
1571wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
1572{
1573	intintobjargproc func = (intintobjargproc)wrapped;
1574	int i, j, res;
1575	PyObject *value;
1576
1577	if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
1578		return NULL;
1579	res = (*func)(self, i, j, value);
1580	if (res == -1 && PyErr_Occurred())
1581		return NULL;
1582	Py_INCREF(Py_None);
1583	return Py_None;
1584}
1585
1586static struct wrapperbase tab_setslice[] = {
1587	{"__setslice__", (wrapperfunc)wrap_intintobjargproc,
1588	 "x.__setslice__(i, j, y) <==> x[i:j]=y"},
1589	{0}
1590};
1591
1592/* XXX objobjproc is a misnomer; should be objargpred */
1593static PyObject *
1594wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
1595{
1596	objobjproc func = (objobjproc)wrapped;
1597	int res;
1598	PyObject *value;
1599
1600	if (!PyArg_ParseTuple(args, "O", &value))
1601		return NULL;
1602	res = (*func)(self, value);
1603	if (res == -1 && PyErr_Occurred())
1604		return NULL;
1605	return PyInt_FromLong((long)res);
1606}
1607
1608static struct wrapperbase tab_contains[] = {
1609	{"__contains__", (wrapperfunc)wrap_objobjproc,
1610	 "x.__contains__(y) <==> y in x"},
1611	{0}
1612};
1613
1614static PyObject *
1615wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
1616{
1617	objobjargproc func = (objobjargproc)wrapped;
1618	int res;
1619	PyObject *key, *value;
1620
1621	if (!PyArg_ParseTuple(args, "OO", &key, &value))
1622		return NULL;
1623	res = (*func)(self, key, value);
1624	if (res == -1 && PyErr_Occurred())
1625		return NULL;
1626	Py_INCREF(Py_None);
1627	return Py_None;
1628}
1629
1630static PyObject *
1631wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
1632{
1633	objobjargproc func = (objobjargproc)wrapped;
1634	int res;
1635	PyObject *key;
1636
1637	if (!PyArg_ParseTuple(args, "O", &key))
1638		return NULL;
1639	res = (*func)(self, key, NULL);
1640	if (res == -1 && PyErr_Occurred())
1641		return NULL;
1642	Py_INCREF(Py_None);
1643	return Py_None;
1644}
1645
1646static struct wrapperbase tab_setitem[] = {
1647	{"__setitem__", (wrapperfunc)wrap_objobjargproc,
1648	 "x.__setitem__(y, z) <==> x[y]=z"},
1649	{"__delitem__", (wrapperfunc)wrap_delitem,
1650	 "x.__delitem__(y) <==> del x[y]"},
1651	{0}
1652};
1653
1654static PyObject *
1655wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
1656{
1657	cmpfunc func = (cmpfunc)wrapped;
1658	int res;
1659	PyObject *other;
1660
1661	if (!PyArg_ParseTuple(args, "O", &other))
1662		return NULL;
1663	res = (*func)(self, other);
1664	if (PyErr_Occurred())
1665		return NULL;
1666	return PyInt_FromLong((long)res);
1667}
1668
1669static struct wrapperbase tab_cmp[] = {
1670	{"__cmp__", (wrapperfunc)wrap_cmpfunc,
1671	 "x.__cmp__(y) <==> cmp(x,y)"},
1672	{0}
1673};
1674
1675static struct wrapperbase tab_repr[] = {
1676	{"__repr__", (wrapperfunc)wrap_unaryfunc,
1677	 "x.__repr__() <==> repr(x)"},
1678	{0}
1679};
1680
1681static struct wrapperbase tab_getattr[] = {
1682	{"__getattr__", (wrapperfunc)wrap_binaryfunc,
1683	 "x.__getattr__('name') <==> x.name"},
1684	{0}
1685};
1686
1687static PyObject *
1688wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
1689{
1690	setattrofunc func = (setattrofunc)wrapped;
1691	int res;
1692	PyObject *name, *value;
1693
1694	if (!PyArg_ParseTuple(args, "OO", &name, &value))
1695		return NULL;
1696	res = (*func)(self, name, value);
1697	if (res < 0)
1698		return NULL;
1699	Py_INCREF(Py_None);
1700	return Py_None;
1701}
1702
1703static PyObject *
1704wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
1705{
1706	setattrofunc func = (setattrofunc)wrapped;
1707	int res;
1708	PyObject *name;
1709
1710	if (!PyArg_ParseTuple(args, "O", &name))
1711		return NULL;
1712	res = (*func)(self, name, NULL);
1713	if (res < 0)
1714		return NULL;
1715	Py_INCREF(Py_None);
1716	return Py_None;
1717}
1718
1719static struct wrapperbase tab_setattr[] = {
1720	{"__setattr__", (wrapperfunc)wrap_setattr,
1721	 "x.__setattr__('name', value) <==> x.name = value"},
1722	{"__delattr__", (wrapperfunc)wrap_delattr,
1723	 "x.__delattr__('name') <==> del x.name"},
1724	{0}
1725};
1726
1727static PyObject *
1728wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
1729{
1730	hashfunc func = (hashfunc)wrapped;
1731	long res;
1732
1733	if (!PyArg_ParseTuple(args, ""))
1734		return NULL;
1735	res = (*func)(self);
1736	if (res == -1 && PyErr_Occurred())
1737		return NULL;
1738	return PyInt_FromLong(res);
1739}
1740
1741static struct wrapperbase tab_hash[] = {
1742	{"__hash__", (wrapperfunc)wrap_hashfunc,
1743	 "x.__hash__() <==> hash(x)"},
1744	{0}
1745};
1746
1747static PyObject *
1748wrap_call(PyObject *self, PyObject *args, void *wrapped)
1749{
1750	ternaryfunc func = (ternaryfunc)wrapped;
1751
1752	/* XXX What about keyword arguments? */
1753	return (*func)(self, args, NULL);
1754}
1755
1756static struct wrapperbase tab_call[] = {
1757	{"__call__", (wrapperfunc)wrap_call,
1758	 "x.__call__(...) <==> x(...)"},
1759	{0}
1760};
1761
1762static struct wrapperbase tab_str[] = {
1763	{"__str__", (wrapperfunc)wrap_unaryfunc,
1764	 "x.__str__() <==> str(x)"},
1765	{0}
1766};
1767
1768static PyObject *
1769wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
1770{
1771	richcmpfunc func = (richcmpfunc)wrapped;
1772	PyObject *other;
1773
1774	if (!PyArg_ParseTuple(args, "O", &other))
1775		return NULL;
1776	return (*func)(self, other, op);
1777}
1778
1779#undef RICHCMP_WRAPPER
1780#define RICHCMP_WRAPPER(NAME, OP) \
1781static PyObject * \
1782richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
1783{ \
1784	return wrap_richcmpfunc(self, args, wrapped, OP); \
1785}
1786
1787RICHCMP_WRAPPER(lt, Py_LT)
1788RICHCMP_WRAPPER(le, Py_LE)
1789RICHCMP_WRAPPER(eq, Py_EQ)
1790RICHCMP_WRAPPER(ne, Py_NE)
1791RICHCMP_WRAPPER(gt, Py_GT)
1792RICHCMP_WRAPPER(ge, Py_GE)
1793
1794#undef RICHCMP_ENTRY
1795#define RICHCMP_ENTRY(NAME, EXPR) \
1796	{"__" #NAME "__", (wrapperfunc)richcmp_##NAME, \
1797	 "x.__" #NAME "__(y) <==> " EXPR}
1798
1799static struct wrapperbase tab_richcmp[] = {
1800	RICHCMP_ENTRY(lt, "x<y"),
1801	RICHCMP_ENTRY(le, "x<=y"),
1802	RICHCMP_ENTRY(eq, "x==y"),
1803	RICHCMP_ENTRY(ne, "x!=y"),
1804	RICHCMP_ENTRY(gt, "x>y"),
1805	RICHCMP_ENTRY(ge, "x>=y"),
1806	{0}
1807};
1808
1809static struct wrapperbase tab_iter[] = {
1810	{"__iter__", (wrapperfunc)wrap_unaryfunc, "x.__iter__() <==> iter(x)"},
1811	{0}
1812};
1813
1814static PyObject *
1815wrap_next(PyObject *self, PyObject *args, void *wrapped)
1816{
1817	unaryfunc func = (unaryfunc)wrapped;
1818	PyObject *res;
1819
1820	if (!PyArg_ParseTuple(args, ""))
1821		return NULL;
1822	res = (*func)(self);
1823	if (res == NULL && !PyErr_Occurred())
1824		PyErr_SetNone(PyExc_StopIteration);
1825	return res;
1826}
1827
1828static struct wrapperbase tab_next[] = {
1829	{"next", (wrapperfunc)wrap_next,
1830		"x.next() -> the next value, or raise StopIteration"},
1831	{0}
1832};
1833
1834static PyObject *
1835wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
1836{
1837	descrgetfunc func = (descrgetfunc)wrapped;
1838	PyObject *obj;
1839	PyObject *type = NULL;
1840
1841	if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
1842		return NULL;
1843	if (type == NULL)
1844		type = (PyObject *)obj->ob_type;
1845	return (*func)(self, obj, type);
1846}
1847
1848static struct wrapperbase tab_descr_get[] = {
1849	{"__get__", (wrapperfunc)wrap_descr_get,
1850	 "descr.__get__(obj, type) -> value"},
1851	{0}
1852};
1853
1854static PyObject *
1855wrap_descrsetfunc(PyObject *self, PyObject *args, void *wrapped)
1856{
1857	descrsetfunc func = (descrsetfunc)wrapped;
1858	PyObject *obj, *value;
1859	int ret;
1860
1861	if (!PyArg_ParseTuple(args, "OO", &obj, &value))
1862		return NULL;
1863	ret = (*func)(self, obj, value);
1864	if (ret < 0)
1865		return NULL;
1866	Py_INCREF(Py_None);
1867	return Py_None;
1868}
1869
1870static struct wrapperbase tab_descr_set[] = {
1871	{"__set__", (wrapperfunc)wrap_descrsetfunc,
1872	 "descr.__set__(obj, value)"},
1873	{0}
1874};
1875
1876static PyObject *
1877wrap_init(PyObject *self, PyObject *args, void *wrapped)
1878{
1879	initproc func = (initproc)wrapped;
1880
1881	/* XXX What about keyword arguments? */
1882	if (func(self, args, NULL) < 0)
1883		return NULL;
1884	Py_INCREF(Py_None);
1885	return Py_None;
1886}
1887
1888static struct wrapperbase tab_init[] = {
1889	{"__init__", (wrapperfunc)wrap_init,
1890	 "x.__init__(...) initializes x; "
1891	 "see x.__type__.__doc__ for signature"},
1892	{0}
1893};
1894
1895static PyObject *
1896tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
1897{
1898	PyTypeObject *type, *subtype;
1899	PyObject *arg0, *res;
1900
1901	if (self == NULL || !PyType_Check(self))
1902		Py_FatalError("__new__() called with non-type 'self'");
1903	type = (PyTypeObject *)self;
1904	if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
1905		PyErr_SetString(PyExc_TypeError,
1906				"T.__new__(): not enough arguments");
1907		return NULL;
1908	}
1909	arg0 = PyTuple_GET_ITEM(args, 0);
1910	if (!PyType_Check(arg0)) {
1911		PyErr_SetString(PyExc_TypeError,
1912				"T.__new__(S): S is not a type object");
1913		return NULL;
1914	}
1915	subtype = (PyTypeObject *)arg0;
1916	if (!PyType_IsSubtype(subtype, type)) {
1917		PyErr_SetString(PyExc_TypeError,
1918				"T.__new__(S): S is not a subtype of T");
1919		return NULL;
1920	}
1921	args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
1922	if (args == NULL)
1923		return NULL;
1924	res = type->tp_new(subtype, args, kwds);
1925	Py_DECREF(args);
1926	return res;
1927}
1928
1929static struct PyMethodDef tp_new_methoddef[] = {
1930	{"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
1931	 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
1932	{0}
1933};
1934
1935static int
1936add_tp_new_wrapper(PyTypeObject *type)
1937{
1938	PyObject *func;
1939
1940	if (PyDict_GetItemString(type->tp_defined, "__new__") != NULL)
1941		return 0;
1942	func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
1943	if (func == NULL)
1944		return -1;
1945	return PyDict_SetItemString(type->tp_defined, "__new__", func);
1946}
1947
1948static int
1949add_wrappers(PyTypeObject *type, struct wrapperbase *wraps, void *wrapped)
1950{
1951	PyObject *dict = type->tp_defined;
1952
1953	for (; wraps->name != NULL; wraps++) {
1954		PyObject *descr;
1955		if (PyDict_GetItemString(dict, wraps->name))
1956			continue;
1957		descr = PyDescr_NewWrapper(type, wraps, wrapped);
1958		if (descr == NULL)
1959			return -1;
1960		if (PyDict_SetItemString(dict, wraps->name, descr) < 0)
1961			return -1;
1962		Py_DECREF(descr);
1963	}
1964	return 0;
1965}
1966
1967/* This function is called by PyType_Ready() to populate the type's
1968   dictionary with method descriptors for function slots.  For each
1969   function slot (like tp_repr) that's defined in the type, one or
1970   more corresponding descriptors are added in the type's tp_defined
1971   dictionary under the appropriate name (like __repr__).  Some
1972   function slots cause more than one descriptor to be added (for
1973   example, the nb_add slot adds both __add__ and __radd__
1974   descriptors) and some function slots compete for the same
1975   descriptor (for example both sq_item and mp_subscript generate a
1976   __getitem__ descriptor).  This only adds new descriptors and
1977   doesn't overwrite entries in tp_defined that were previously
1978   defined.  The descriptors contain a reference to the C function
1979   they must call, so that it's safe if they are copied into a
1980   subtype's __dict__ and the subtype has a different C function in
1981   its slot -- calling the method defined by the descriptor will call
1982   the C function that was used to create it, rather than the C
1983   function present in the slot when it is called.  (This is important
1984   because a subtype may have a C function in the slot that calls the
1985   method from the dictionary, and we want to avoid infinite recursion
1986   here.) */
1987
1988static int
1989add_operators(PyTypeObject *type)
1990{
1991	PySequenceMethods *sq;
1992	PyMappingMethods *mp;
1993	PyNumberMethods *nb;
1994
1995#undef ADD
1996#define ADD(SLOT, TABLE) \
1997		if (SLOT) { \
1998			if (add_wrappers(type, TABLE, (void *)(SLOT)) < 0) \
1999				return -1; \
2000		}
2001
2002	if ((sq = type->tp_as_sequence) != NULL) {
2003		ADD(sq->sq_length, tab_len);
2004		ADD(sq->sq_concat, tab_concat);
2005		ADD(sq->sq_repeat, tab_mul_int);
2006		ADD(sq->sq_item, tab_getitem_int);
2007		ADD(sq->sq_slice, tab_getslice);
2008		ADD(sq->sq_ass_item, tab_setitem_int);
2009		ADD(sq->sq_ass_slice, tab_setslice);
2010		ADD(sq->sq_contains, tab_contains);
2011		ADD(sq->sq_inplace_concat, tab_iadd);
2012		ADD(sq->sq_inplace_repeat, tab_imul_int);
2013	}
2014
2015	if ((mp = type->tp_as_mapping) != NULL) {
2016		if (sq->sq_length == NULL)
2017			ADD(mp->mp_length, tab_len);
2018		ADD(mp->mp_subscript, tab_getitem);
2019		ADD(mp->mp_ass_subscript, tab_setitem);
2020	}
2021
2022	/* We don't support "old-style numbers" because their binary
2023	   operators require that both arguments have the same type;
2024	   the wrappers here only work for new-style numbers. */
2025	if ((type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2026	    (nb = type->tp_as_number) != NULL) {
2027		ADD(nb->nb_add, tab_add);
2028		ADD(nb->nb_subtract, tab_sub);
2029		ADD(nb->nb_multiply, tab_mul);
2030		ADD(nb->nb_divide, tab_div);
2031		ADD(nb->nb_remainder, tab_mod);
2032		ADD(nb->nb_divmod, tab_divmod);
2033		ADD(nb->nb_power, tab_pow);
2034		ADD(nb->nb_negative, tab_neg);
2035		ADD(nb->nb_positive, tab_pos);
2036		ADD(nb->nb_absolute, tab_abs);
2037		ADD(nb->nb_nonzero, tab_nonzero);
2038		ADD(nb->nb_invert, tab_invert);
2039		ADD(nb->nb_lshift, tab_lshift);
2040		ADD(nb->nb_rshift, tab_rshift);
2041		ADD(nb->nb_and, tab_and);
2042		ADD(nb->nb_xor, tab_xor);
2043		ADD(nb->nb_or, tab_or);
2044		/* We don't support coerce() -- see above comment */
2045		ADD(nb->nb_int, tab_int);
2046		ADD(nb->nb_long, tab_long);
2047		ADD(nb->nb_float, tab_float);
2048		ADD(nb->nb_oct, tab_oct);
2049		ADD(nb->nb_hex, tab_hex);
2050		ADD(nb->nb_inplace_add, tab_iadd);
2051		ADD(nb->nb_inplace_subtract, tab_isub);
2052		ADD(nb->nb_inplace_multiply, tab_imul);
2053		ADD(nb->nb_inplace_divide, tab_idiv);
2054		ADD(nb->nb_inplace_remainder, tab_imod);
2055		ADD(nb->nb_inplace_power, tab_ipow);
2056		ADD(nb->nb_inplace_lshift, tab_ilshift);
2057		ADD(nb->nb_inplace_rshift, tab_irshift);
2058		ADD(nb->nb_inplace_and, tab_iand);
2059		ADD(nb->nb_inplace_xor, tab_ixor);
2060		ADD(nb->nb_inplace_or, tab_ior);
2061	}
2062
2063	ADD(type->tp_getattro, tab_getattr);
2064	ADD(type->tp_setattro, tab_setattr);
2065	ADD(type->tp_compare, tab_cmp);
2066	ADD(type->tp_repr, tab_repr);
2067	ADD(type->tp_hash, tab_hash);
2068	ADD(type->tp_call, tab_call);
2069	ADD(type->tp_str, tab_str);
2070	ADD(type->tp_richcompare, tab_richcmp);
2071	ADD(type->tp_iter, tab_iter);
2072	ADD(type->tp_iternext, tab_next);
2073	ADD(type->tp_descr_get, tab_descr_get);
2074	ADD(type->tp_descr_set, tab_descr_set);
2075	ADD(type->tp_init, tab_init);
2076
2077	if (type->tp_new != NULL) {
2078		if (add_tp_new_wrapper(type) < 0)
2079			return -1;
2080	}
2081
2082	return 0;
2083}
2084
2085/* Slot wrappers that call the corresponding __foo__ slot.  See comments
2086   below at override_slots() for more explanation. */
2087
2088#define SLOT0(FUNCNAME, OPSTR) \
2089static PyObject * \
2090FUNCNAME(PyObject *self) \
2091{ \
2092	return PyObject_CallMethod(self, OPSTR, ""); \
2093}
2094
2095#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
2096static PyObject * \
2097FUNCNAME(PyObject *self, ARG1TYPE arg1) \
2098{ \
2099	return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1); \
2100}
2101
2102
2103#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
2104static PyObject * \
2105FUNCNAME(PyObject *self, PyObject *other) \
2106{ \
2107	if (self->ob_type->tp_as_number != NULL && \
2108	    self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2109		PyObject *r; \
2110		r = PyObject_CallMethod( \
2111			self, OPSTR, "O", other); \
2112		if (r != Py_NotImplemented || \
2113		    other->ob_type == self->ob_type) \
2114			return r; \
2115		Py_DECREF(r); \
2116	} \
2117	if (other->ob_type->tp_as_number != NULL && \
2118	    other->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
2119		return PyObject_CallMethod( \
2120			other, ROPSTR, "O", self); \
2121	} \
2122	Py_INCREF(Py_NotImplemented); \
2123	return Py_NotImplemented; \
2124}
2125
2126#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
2127	SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
2128
2129#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2130static PyObject * \
2131FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2132{ \
2133	return PyObject_CallMethod(self, OPSTR, ARGCODES, arg1, arg2); \
2134}
2135
2136static int
2137slot_sq_length(PyObject *self)
2138{
2139	PyObject *res = PyObject_CallMethod(self, "__len__", "");
2140
2141	if (res == NULL)
2142		return -1;
2143	return (int)PyInt_AsLong(res);
2144}
2145
2146SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
2147SLOT1(slot_sq_repeat, "__mul__", int, "i")
2148SLOT1(slot_sq_item, "__getitem__", int, "i")
2149SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
2150
2151static int
2152slot_sq_ass_item(PyObject *self, int index, PyObject *value)
2153{
2154	PyObject *res;
2155
2156	if (value == NULL)
2157		res = PyObject_CallMethod(self, "__delitem__", "i", index);
2158	else
2159		res = PyObject_CallMethod(self, "__setitem__",
2160					  "iO", index, value);
2161	if (res == NULL)
2162		return -1;
2163	Py_DECREF(res);
2164	return 0;
2165}
2166
2167static int
2168slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
2169{
2170	PyObject *res;
2171
2172	if (value == NULL)
2173		res = PyObject_CallMethod(self, "__delslice__", "ii", i, j);
2174	else
2175		res = PyObject_CallMethod(self, "__setslice__",
2176					  "iiO", i, j, value);
2177	if (res == NULL)
2178		return -1;
2179	Py_DECREF(res);
2180	return 0;
2181}
2182
2183static int
2184slot_sq_contains(PyObject *self, PyObject *value)
2185{
2186	PyObject *res = PyObject_CallMethod(self, "__contains__", "O", value);
2187	int r;
2188
2189	if (res == NULL)
2190		return -1;
2191	r = PyInt_AsLong(res);
2192	Py_DECREF(res);
2193	return r;
2194}
2195
2196SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
2197SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
2198
2199#define slot_mp_length slot_sq_length
2200
2201SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
2202
2203static int
2204slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
2205{
2206	PyObject *res;
2207
2208	if (value == NULL)
2209		res = PyObject_CallMethod(self, "__delitem__", "O", key);
2210	else
2211		res = PyObject_CallMethod(self, "__setitem__",
2212					  "OO", key, value);
2213	if (res == NULL)
2214		return -1;
2215	Py_DECREF(res);
2216	return 0;
2217}
2218
2219SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
2220SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
2221SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
2222SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
2223SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
2224SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
2225
2226staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
2227
2228SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
2229	     nb_power, "__pow__", "__rpow__")
2230
2231static PyObject *
2232slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
2233{
2234	if (modulus == Py_None)
2235		return slot_nb_power_binary(self, other);
2236	/* Three-arg power doesn't use __rpow__ */
2237	return PyObject_CallMethod(self, "__pow__", "OO", other, modulus);
2238}
2239
2240SLOT0(slot_nb_negative, "__neg__")
2241SLOT0(slot_nb_positive, "__pos__")
2242SLOT0(slot_nb_absolute, "__abs__")
2243
2244static int
2245slot_nb_nonzero(PyObject *self)
2246{
2247	PyObject *res = PyObject_CallMethod(self, "__nonzero__", "");
2248
2249	if (res == NULL)
2250		return -1;
2251	return (int)PyInt_AsLong(res);
2252}
2253
2254SLOT0(slot_nb_invert, "__invert__")
2255SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
2256SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
2257SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
2258SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
2259SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
2260/* Not coerce() */
2261SLOT0(slot_nb_int, "__int__")
2262SLOT0(slot_nb_long, "__long__")
2263SLOT0(slot_nb_float, "__float__")
2264SLOT0(slot_nb_oct, "__oct__")
2265SLOT0(slot_nb_hex, "__hex__")
2266SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
2267SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
2268SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
2269SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
2270SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
2271SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
2272SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
2273SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
2274SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
2275SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
2276SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
2277SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
2278	 "__floordiv__", "__rfloordiv__")
2279SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
2280SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
2281SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
2282
2283static int
2284slot_tp_compare(PyObject *self, PyObject *other)
2285{
2286	PyObject *res = PyObject_CallMethod(self, "__cmp__", "O", other);
2287	long r;
2288
2289	if (res == NULL)
2290		return -1;
2291	r = PyInt_AsLong(res);
2292	Py_DECREF(res);
2293	return (int)r;
2294}
2295
2296SLOT0(slot_tp_repr, "__repr__")
2297
2298static long
2299slot_tp_hash(PyObject *self)
2300{
2301	PyObject *res = PyObject_CallMethod(self, "__hash__", "");
2302	long h;
2303
2304	if (res == NULL)
2305		return -1;
2306	h = PyInt_AsLong(res);
2307	if (h == -1 && !PyErr_Occurred())
2308		h = -2;
2309	return h;
2310}
2311
2312static PyObject *
2313slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
2314{
2315	PyObject *meth = PyObject_GetAttrString(self, "__call__");
2316	PyObject *res;
2317
2318	if (meth == NULL)
2319		return NULL;
2320	res = PyObject_Call(meth, args, kwds);
2321	Py_DECREF(meth);
2322	return res;
2323}
2324
2325SLOT0(slot_tp_str, "__str__")
2326
2327static PyObject *
2328slot_tp_getattro(PyObject *self, PyObject *name)
2329{
2330	PyTypeObject *tp = self->ob_type;
2331	PyObject *getattr;
2332	static PyObject *getattr_str = NULL;
2333
2334	if (getattr_str == NULL) {
2335		getattr_str = PyString_InternFromString("__getattr__");
2336		if (getattr_str == NULL)
2337			return NULL;
2338	}
2339	getattr = _PyType_Lookup(tp, getattr_str);
2340	if (getattr == NULL)
2341		return PyObject_GenericGetAttr(self, name);
2342	return PyObject_CallFunction(getattr, "OO", self, name);
2343}
2344
2345static int
2346slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
2347{
2348	PyObject *res;
2349
2350	if (value == NULL)
2351		res = PyObject_CallMethod(self, "__delattr__", "O", name);
2352	else
2353		res = PyObject_CallMethod(self, "__setattr__",
2354					  "OO", name, value);
2355	if (res == NULL)
2356		return -1;
2357	Py_DECREF(res);
2358	return 0;
2359}
2360
2361/* Map rich comparison operators to their __xx__ namesakes */
2362static char *name_op[] = {
2363	"__lt__",
2364	"__le__",
2365	"__eq__",
2366	"__ne__",
2367	"__gt__",
2368	"__ge__",
2369};
2370
2371static PyObject *
2372slot_tp_richcompare(PyObject *self, PyObject *other, int op)
2373{
2374	PyObject *meth = PyObject_GetAttrString(self, name_op[op]);
2375	PyObject *res;
2376
2377	if (meth == NULL)
2378		return NULL;
2379	res = PyObject_CallFunction(meth, "O", other);
2380	Py_DECREF(meth);
2381	return res;
2382}
2383
2384SLOT0(slot_tp_iter, "__iter__")
2385
2386static PyObject *
2387slot_tp_iternext(PyObject *self)
2388{
2389	return PyObject_CallMethod(self, "next", "");
2390}
2391
2392SLOT2(slot_tp_descr_get, "__get__", PyObject *, PyObject *, "OO")
2393
2394static int
2395slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
2396{
2397	PyObject *res = PyObject_CallMethod(self, "__set__",
2398					    "OO", target, value);
2399	if (res == NULL)
2400		return -1;
2401	Py_DECREF(res);
2402	return 0;
2403}
2404
2405static int
2406slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
2407{
2408	PyObject *meth = PyObject_GetAttrString(self, "__init__");
2409	PyObject *res;
2410
2411	if (meth == NULL)
2412		return -1;
2413	res = PyObject_Call(meth, args, kwds);
2414	Py_DECREF(meth);
2415	if (res == NULL)
2416		return -1;
2417	Py_DECREF(res);
2418	return 0;
2419}
2420
2421static PyObject *
2422slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2423{
2424	PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
2425	PyObject *newargs, *x;
2426	int i, n;
2427
2428	if (func == NULL)
2429		return NULL;
2430	assert(PyTuple_Check(args));
2431	n = PyTuple_GET_SIZE(args);
2432	newargs = PyTuple_New(n+1);
2433	if (newargs == NULL)
2434		return NULL;
2435	Py_INCREF(type);
2436	PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
2437	for (i = 0; i < n; i++) {
2438		x = PyTuple_GET_ITEM(args, i);
2439		Py_INCREF(x);
2440		PyTuple_SET_ITEM(newargs, i+1, x);
2441	}
2442	x = PyObject_Call(func, newargs, kwds);
2443	Py_DECREF(func);
2444	return x;
2445}
2446
2447/* This is called at the very end of type_new() (even after
2448   PyType_Ready()) to complete the initialization of dynamic types.
2449   The dict argument is the dictionary argument passed to type_new(),
2450   which is the local namespace of the class statement, in other
2451   words, it contains the methods.  For each special method (like
2452   __repr__) defined in the dictionary, the corresponding function
2453   slot in the type object (like tp_repr) is set to a special function
2454   whose name is 'slot_' followed by the slot name and whose signature
2455   is whatever is required for that slot.  These slot functions look
2456   up the corresponding method in the type's dictionary and call it.
2457   The slot functions have to take care of the various peculiarities
2458   of the mapping between slots and special methods, such as mapping
2459   one slot to multiple methods (tp_richcompare <--> __le__, __lt__
2460   etc.)  or mapping multiple slots to a single method (sq_item,
2461   mp_subscript <--> __getitem__). */
2462
2463static void
2464override_slots(PyTypeObject *type, PyObject *dict)
2465{
2466	PySequenceMethods *sq = type->tp_as_sequence;
2467	PyMappingMethods *mp = type->tp_as_mapping;
2468	PyNumberMethods *nb = type->tp_as_number;
2469
2470#define SQSLOT(OPNAME, SLOTNAME, FUNCNAME) \
2471	if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
2472		sq->SLOTNAME = FUNCNAME; \
2473	}
2474
2475#define MPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
2476	if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
2477		mp->SLOTNAME = FUNCNAME; \
2478	}
2479
2480#define NBSLOT(OPNAME, SLOTNAME, FUNCNAME) \
2481	if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
2482		nb->SLOTNAME = FUNCNAME; \
2483	}
2484
2485#define TPSLOT(OPNAME, SLOTNAME, FUNCNAME) \
2486	if (dict == NULL || PyDict_GetItemString(dict, OPNAME)) { \
2487		type->SLOTNAME = FUNCNAME; \
2488	}
2489
2490	SQSLOT("__len__", sq_length, slot_sq_length);
2491	SQSLOT("__add__", sq_concat, slot_sq_concat);
2492	SQSLOT("__mul__", sq_repeat, slot_sq_repeat);
2493	SQSLOT("__getitem__", sq_item, slot_sq_item);
2494	SQSLOT("__getslice__", sq_slice, slot_sq_slice);
2495	SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item);
2496	SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item);
2497	SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice);
2498	SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice);
2499	SQSLOT("__contains__", sq_contains, slot_sq_contains);
2500	SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat);
2501	SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat);
2502
2503	MPSLOT("__len__", mp_length, slot_mp_length);
2504	MPSLOT("__getitem__", mp_subscript, slot_mp_subscript);
2505	MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript);
2506	MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript);
2507
2508	NBSLOT("__add__", nb_add, slot_nb_add);
2509	NBSLOT("__sub__", nb_subtract, slot_nb_subtract);
2510	NBSLOT("__mul__", nb_multiply, slot_nb_multiply);
2511	NBSLOT("__div__", nb_divide, slot_nb_divide);
2512	NBSLOT("__mod__", nb_remainder, slot_nb_remainder);
2513	NBSLOT("__divmod__", nb_divmod, slot_nb_divmod);
2514	NBSLOT("__pow__", nb_power, slot_nb_power);
2515	NBSLOT("__neg__", nb_negative, slot_nb_negative);
2516	NBSLOT("__pos__", nb_positive, slot_nb_positive);
2517	NBSLOT("__abs__", nb_absolute, slot_nb_absolute);
2518	NBSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero);
2519	NBSLOT("__invert__", nb_invert, slot_nb_invert);
2520	NBSLOT("__lshift__", nb_lshift, slot_nb_lshift);
2521	NBSLOT("__rshift__", nb_rshift, slot_nb_rshift);
2522	NBSLOT("__and__", nb_and, slot_nb_and);
2523	NBSLOT("__xor__", nb_xor, slot_nb_xor);
2524	NBSLOT("__or__", nb_or, slot_nb_or);
2525	/* Not coerce() */
2526	NBSLOT("__int__", nb_int, slot_nb_int);
2527	NBSLOT("__long__", nb_long, slot_nb_long);
2528	NBSLOT("__float__", nb_float, slot_nb_float);
2529	NBSLOT("__oct__", nb_oct, slot_nb_oct);
2530	NBSLOT("__hex__", nb_hex, slot_nb_hex);
2531	NBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add);
2532	NBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract);
2533	NBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply);
2534	NBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide);
2535	NBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder);
2536	NBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power);
2537	NBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift);
2538	NBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift);
2539	NBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and);
2540	NBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor);
2541	NBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or);
2542	NBSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide);
2543	NBSLOT("__truediv__", nb_true_divide, slot_nb_true_divide);
2544	NBSLOT("__ifloordiv__", nb_inplace_floor_divide,
2545	       slot_nb_inplace_floor_divide);
2546	NBSLOT("__itruediv__", nb_inplace_true_divide,
2547	       slot_nb_inplace_true_divide);
2548
2549	if (dict == NULL ||
2550	    PyDict_GetItemString(dict, "__str__") ||
2551	    PyDict_GetItemString(dict, "__repr__"))
2552		type->tp_print = NULL;
2553
2554	TPSLOT("__cmp__", tp_compare, slot_tp_compare);
2555	TPSLOT("__repr__", tp_repr, slot_tp_repr);
2556	TPSLOT("__hash__", tp_hash, slot_tp_hash);
2557	TPSLOT("__call__", tp_call, slot_tp_call);
2558	TPSLOT("__str__", tp_str, slot_tp_str);
2559	TPSLOT("__getattr__", tp_getattro, slot_tp_getattro);
2560	TPSLOT("__setattr__", tp_setattro, slot_tp_setattro);
2561	TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare);
2562	TPSLOT("__le__", tp_richcompare, slot_tp_richcompare);
2563	TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare);
2564	TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare);
2565	TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare);
2566	TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare);
2567	TPSLOT("__iter__", tp_iter, slot_tp_iter);
2568	TPSLOT("next", tp_iternext, slot_tp_iternext);
2569	TPSLOT("__get__", tp_descr_get, slot_tp_descr_get);
2570	TPSLOT("__set__", tp_descr_set, slot_tp_descr_set);
2571	TPSLOT("__init__", tp_init, slot_tp_init);
2572	TPSLOT("__new__", tp_new, slot_tp_new);
2573}
2574