typeobject.c revision 83245b58280a7679da0fe7216f36353e44ddf859
1/* Type object implementation */
2
3#include "Python.h"
4#include "structmember.h"
5
6#include <ctype.h>
7
8static PyMemberDef type_members[] = {
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	{"__weakrefoffset__", T_LONG,
13	 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
14	{"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
15	{"__dictoffset__", T_LONG,
16	 offsetof(PyTypeObject, tp_dictoffset), READONLY},
17	{"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
18	{0}
19};
20
21static PyObject *
22type_name(PyTypeObject *type, void *context)
23{
24	char *s;
25
26	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
27		PyHeapTypeObject* et = (PyHeapTypeObject*)type;
28
29		Py_INCREF(et->name);
30		return et->name;
31	}
32	else {
33		s = strrchr(type->tp_name, '.');
34		if (s == NULL)
35			s = type->tp_name;
36		else
37			s++;
38		return PyString_FromString(s);
39	}
40}
41
42static int
43type_set_name(PyTypeObject *type, PyObject *value, void *context)
44{
45	PyHeapTypeObject* et;
46
47	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
48		PyErr_Format(PyExc_TypeError,
49			     "can't set %s.__name__", type->tp_name);
50		return -1;
51	}
52	if (!value) {
53		PyErr_Format(PyExc_TypeError,
54			     "can't delete %s.__name__", type->tp_name);
55		return -1;
56	}
57	if (!PyString_Check(value)) {
58		PyErr_Format(PyExc_TypeError,
59			     "can only assign string to %s.__name__, not '%s'",
60			     type->tp_name, value->ob_type->tp_name);
61		return -1;
62	}
63	if (strlen(PyString_AS_STRING(value))
64	    != (size_t)PyString_GET_SIZE(value)) {
65		PyErr_Format(PyExc_ValueError,
66			     "__name__ must not contain null bytes");
67		return -1;
68	}
69
70	et = (PyHeapTypeObject*)type;
71
72	Py_INCREF(value);
73
74	Py_DECREF(et->name);
75	et->name = value;
76
77	type->tp_name = PyString_AS_STRING(value);
78
79	return 0;
80}
81
82static PyObject *
83type_module(PyTypeObject *type, void *context)
84{
85	PyObject *mod;
86	char *s;
87
88	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
89		mod = PyDict_GetItemString(type->tp_dict, "__module__");
90		Py_XINCREF(mod);
91		return mod;
92	}
93	else {
94		s = strrchr(type->tp_name, '.');
95		if (s != NULL)
96			return PyString_FromStringAndSize(
97				type->tp_name, (int)(s - type->tp_name));
98		return PyString_FromString("__builtin__");
99	}
100}
101
102static int
103type_set_module(PyTypeObject *type, PyObject *value, void *context)
104{
105	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
106		PyErr_Format(PyExc_TypeError,
107			     "can't set %s.__module__", type->tp_name);
108		return -1;
109	}
110	if (!value) {
111		PyErr_Format(PyExc_TypeError,
112			     "can't delete %s.__module__", type->tp_name);
113		return -1;
114	}
115
116	return PyDict_SetItemString(type->tp_dict, "__module__", value);
117}
118
119static PyObject *
120type_get_bases(PyTypeObject *type, void *context)
121{
122	Py_INCREF(type->tp_bases);
123	return type->tp_bases;
124}
125
126static PyTypeObject *best_base(PyObject *);
127static int mro_internal(PyTypeObject *);
128static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, char *);
129static int add_subclass(PyTypeObject*, PyTypeObject*);
130static void remove_subclass(PyTypeObject *, PyTypeObject *);
131static void update_all_slots(PyTypeObject *);
132
133static int
134mro_subclasses(PyTypeObject *type, PyObject* temp)
135{
136	PyTypeObject *subclass;
137	PyObject *ref, *subclasses, *old_mro;
138	int i, n;
139
140	subclasses = type->tp_subclasses;
141	if (subclasses == NULL)
142		return 0;
143	assert(PyList_Check(subclasses));
144	n = PyList_GET_SIZE(subclasses);
145	for (i = 0; i < n; i++) {
146		ref = PyList_GET_ITEM(subclasses, i);
147		assert(PyWeakref_CheckRef(ref));
148		subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
149		assert(subclass != NULL);
150		if ((PyObject *)subclass == Py_None)
151			continue;
152		assert(PyType_Check(subclass));
153		old_mro = subclass->tp_mro;
154		if (mro_internal(subclass) < 0) {
155			subclass->tp_mro = old_mro;
156			return -1;
157		}
158		else {
159			PyObject* tuple;
160			tuple = Py_BuildValue("OO", subclass, old_mro);
161			if (!tuple)
162				return -1;
163			if (PyList_Append(temp, tuple) < 0)
164				return -1;
165		}
166		if (mro_subclasses(subclass, temp) < 0)
167			return -1;
168	}
169	return 0;
170}
171
172static int
173type_set_bases(PyTypeObject *type, PyObject *value, void *context)
174{
175	int i, r = 0;
176	PyObject *ob, *temp;
177	PyTypeObject *new_base, *old_base;
178	PyObject *old_bases, *old_mro;
179
180	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
181		PyErr_Format(PyExc_TypeError,
182			     "can't set %s.__bases__", type->tp_name);
183		return -1;
184	}
185	if (!value) {
186		PyErr_Format(PyExc_TypeError,
187			     "can't delete %s.__bases__", type->tp_name);
188		return -1;
189	}
190	if (!PyTuple_Check(value)) {
191		PyErr_Format(PyExc_TypeError,
192		     "can only assign tuple to %s.__bases__, not %s",
193			     type->tp_name, value->ob_type->tp_name);
194		return -1;
195	}
196	if (PyTuple_GET_SIZE(value) == 0) {
197		PyErr_Format(PyExc_TypeError,
198		     "can only assign non-empty tuple to %s.__bases__, not ()",
199			     type->tp_name);
200		return -1;
201	}
202	for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
203		ob = PyTuple_GET_ITEM(value, i);
204		if (!PyClass_Check(ob) && !PyType_Check(ob)) {
205			PyErr_Format(
206				PyExc_TypeError,
207	"%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
208				type->tp_name, ob->ob_type->tp_name);
209			return -1;
210		}
211		if (PyType_Check(ob)) {
212			if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
213				PyErr_SetString(PyExc_TypeError,
214			"a __bases__ item causes an inheritance cycle");
215				return -1;
216			}
217		}
218	}
219
220	new_base = best_base(value);
221
222	if (!new_base) {
223		return -1;
224	}
225
226	if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
227		return -1;
228
229	Py_INCREF(new_base);
230	Py_INCREF(value);
231
232	old_bases = type->tp_bases;
233	old_base = type->tp_base;
234	old_mro = type->tp_mro;
235
236	type->tp_bases = value;
237	type->tp_base = new_base;
238
239	if (mro_internal(type) < 0) {
240		goto bail;
241	}
242
243	temp = PyList_New(0);
244	if (!temp)
245		goto bail;
246
247	r = mro_subclasses(type, temp);
248
249	if (r < 0) {
250		for (i = 0; i < PyList_Size(temp); i++) {
251			PyTypeObject* cls;
252			PyObject* mro;
253			PyArg_ParseTuple(PyList_GetItem(temp, i),
254					 "OO", &cls, &mro);
255			Py_DECREF(cls->tp_mro);
256			cls->tp_mro = mro;
257			Py_INCREF(cls->tp_mro);
258		}
259		Py_DECREF(temp);
260		goto bail;
261	}
262
263	Py_DECREF(temp);
264
265	/* any base that was in __bases__ but now isn't, we
266	   need to remove |type| from its tp_subclasses.
267	   conversely, any class now in __bases__ that wasn't
268	   needs to have |type| added to its subclasses. */
269
270	/* for now, sod that: just remove from all old_bases,
271	   add to all new_bases */
272
273	for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
274		ob = PyTuple_GET_ITEM(old_bases, i);
275		if (PyType_Check(ob)) {
276			remove_subclass(
277				(PyTypeObject*)ob, type);
278		}
279	}
280
281	for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
282		ob = PyTuple_GET_ITEM(value, i);
283		if (PyType_Check(ob)) {
284			if (add_subclass((PyTypeObject*)ob, type) < 0)
285				r = -1;
286		}
287	}
288
289	update_all_slots(type);
290
291	Py_DECREF(old_bases);
292	Py_DECREF(old_base);
293	Py_DECREF(old_mro);
294
295	return r;
296
297  bail:
298	type->tp_bases = old_bases;
299	type->tp_base = old_base;
300	type->tp_mro = old_mro;
301
302	Py_DECREF(value);
303	Py_DECREF(new_base);
304
305	return -1;
306}
307
308static PyObject *
309type_dict(PyTypeObject *type, void *context)
310{
311	if (type->tp_dict == NULL) {
312		Py_INCREF(Py_None);
313		return Py_None;
314	}
315	return PyDictProxy_New(type->tp_dict);
316}
317
318static PyObject *
319type_get_doc(PyTypeObject *type, void *context)
320{
321	PyObject *result;
322	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
323		return PyString_FromString(type->tp_doc);
324	result = PyDict_GetItemString(type->tp_dict, "__doc__");
325	if (result == NULL) {
326		result = Py_None;
327		Py_INCREF(result);
328	}
329	else if (result->ob_type->tp_descr_get) {
330		result = result->ob_type->tp_descr_get(result, NULL,
331						       (PyObject *)type);
332	}
333	else {
334		Py_INCREF(result);
335	}
336	return result;
337}
338
339static PyGetSetDef type_getsets[] = {
340	{"__name__", (getter)type_name, (setter)type_set_name, NULL},
341	{"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
342	{"__module__", (getter)type_module, (setter)type_set_module, NULL},
343	{"__dict__",  (getter)type_dict,  NULL, NULL},
344	{"__doc__", (getter)type_get_doc, NULL, NULL},
345	{0}
346};
347
348static int
349type_compare(PyObject *v, PyObject *w)
350{
351	/* This is called with type objects only. So we
352	   can just compare the addresses. */
353	Py_uintptr_t vv = (Py_uintptr_t)v;
354	Py_uintptr_t ww = (Py_uintptr_t)w;
355	return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
356}
357
358static PyObject *
359type_repr(PyTypeObject *type)
360{
361	PyObject *mod, *name, *rtn;
362	char *kind;
363
364	mod = type_module(type, NULL);
365	if (mod == NULL)
366		PyErr_Clear();
367	else if (!PyString_Check(mod)) {
368		Py_DECREF(mod);
369		mod = NULL;
370	}
371	name = type_name(type, NULL);
372	if (name == NULL)
373		return NULL;
374
375	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
376		kind = "class";
377	else
378		kind = "type";
379
380	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
381		rtn = PyString_FromFormat("<%s '%s.%s'>",
382					  kind,
383					  PyString_AS_STRING(mod),
384					  PyString_AS_STRING(name));
385	}
386	else
387		rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
388
389	Py_XDECREF(mod);
390	Py_DECREF(name);
391	return rtn;
392}
393
394static PyObject *
395type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
396{
397	PyObject *obj;
398
399	if (type->tp_new == NULL) {
400		PyErr_Format(PyExc_TypeError,
401			     "cannot create '%.100s' instances",
402			     type->tp_name);
403		return NULL;
404	}
405
406	obj = type->tp_new(type, args, kwds);
407	if (obj != NULL) {
408		/* Ugly exception: when the call was type(something),
409		   don't call tp_init on the result. */
410		if (type == &PyType_Type &&
411		    PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
412		    (kwds == NULL ||
413		     (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
414			return obj;
415		/* If the returned object is not an instance of type,
416		   it won't be initialized. */
417		if (!PyType_IsSubtype(obj->ob_type, type))
418			return obj;
419		type = obj->ob_type;
420		if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
421		    type->tp_init != NULL &&
422		    type->tp_init(obj, args, kwds) < 0) {
423			Py_DECREF(obj);
424			obj = NULL;
425		}
426	}
427	return obj;
428}
429
430PyObject *
431PyType_GenericAlloc(PyTypeObject *type, int nitems)
432{
433	PyObject *obj;
434	const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
435	/* note that we need to add one, for the sentinel */
436
437	if (PyType_IS_GC(type))
438		obj = _PyObject_GC_Malloc(size);
439	else
440		obj = PyObject_MALLOC(size);
441
442	if (obj == NULL)
443		return PyErr_NoMemory();
444
445	memset(obj, '\0', size);
446
447	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
448		Py_INCREF(type);
449
450	if (type->tp_itemsize == 0)
451		PyObject_INIT(obj, type);
452	else
453		(void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
454
455	if (PyType_IS_GC(type))
456		_PyObject_GC_TRACK(obj);
457	return obj;
458}
459
460PyObject *
461PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
462{
463	return type->tp_alloc(type, 0);
464}
465
466/* Helpers for subtyping */
467
468static int
469traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
470{
471	int i, n;
472	PyMemberDef *mp;
473
474	n = type->ob_size;
475	mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
476	for (i = 0; i < n; i++, mp++) {
477		if (mp->type == T_OBJECT_EX) {
478			char *addr = (char *)self + mp->offset;
479			PyObject *obj = *(PyObject **)addr;
480			if (obj != NULL) {
481				int err = visit(obj, arg);
482				if (err)
483					return err;
484			}
485		}
486	}
487	return 0;
488}
489
490static int
491subtype_traverse(PyObject *self, visitproc visit, void *arg)
492{
493	PyTypeObject *type, *base;
494	traverseproc basetraverse;
495
496	/* Find the nearest base with a different tp_traverse,
497	   and traverse slots while we're at it */
498	type = self->ob_type;
499	base = type;
500	while ((basetraverse = base->tp_traverse) == subtype_traverse) {
501		if (base->ob_size) {
502			int err = traverse_slots(base, self, visit, arg);
503			if (err)
504				return err;
505		}
506		base = base->tp_base;
507		assert(base);
508	}
509
510	if (type->tp_dictoffset != base->tp_dictoffset) {
511		PyObject **dictptr = _PyObject_GetDictPtr(self);
512		if (dictptr && *dictptr) {
513			int err = visit(*dictptr, arg);
514			if (err)
515				return err;
516		}
517	}
518
519	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
520		/* For a heaptype, the instances count as references
521		   to the type.  Traverse the type so the collector
522		   can find cycles involving this link. */
523		int err = visit((PyObject *)type, arg);
524		if (err)
525			return err;
526	}
527
528	if (basetraverse)
529		return basetraverse(self, visit, arg);
530	return 0;
531}
532
533static void
534clear_slots(PyTypeObject *type, PyObject *self)
535{
536	int i, n;
537	PyMemberDef *mp;
538
539	n = type->ob_size;
540	mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
541	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) {
546				Py_DECREF(obj);
547				*(PyObject **)addr = NULL;
548			}
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 */
561	type = self->ob_type;
562	base = type;
563	while ((baseclear = base->tp_clear) == subtype_clear) {
564		if (base->ob_size)
565			clear_slots(base, self);
566		base = base->tp_base;
567		assert(base);
568	}
569
570	/* There's no need to clear the instance dict (if any);
571	   the collector will call its tp_clear handler. */
572
573	if (baseclear)
574		return baseclear(self);
575	return 0;
576}
577
578static void
579subtype_dealloc(PyObject *self)
580{
581	PyTypeObject *type, *base;
582	destructor basedealloc;
583
584	/* Extract the type; we expect it to be a heap type */
585	type = self->ob_type;
586	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
587
588	/* 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 */
598		if (type->tp_del) {
599			type->tp_del(self);
600			if (self->ob_refcnt > 0)
601				return;
602		}
603
604		/* Find the nearest base with a different tp_dealloc */
605		base = type;
606		while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
607			assert(base->ob_size == 0);
608			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 */
626	/* See explanation at end of function for full disclosure */
627	PyObject_GC_UnTrack(self);
628	++_PyTrash_delete_nesting;
629	Py_TRASHCAN_SAFE_BEGIN(self);
630	--_PyTrash_delete_nesting;
631	_PyObject_GC_TRACK(self); /* We'll untrack for real later */
632
633	/* Maybe call finalizer; exit early if resurrected */
634	if (type->tp_del) {
635		type->tp_del(self);
636		if (self->ob_refcnt > 0)
637			goto endlabel;
638	}
639
640	/* Find the nearest base with a different tp_dealloc
641	   and clear slots while we're at it */
642	base = type;
643	while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
644		if (base->ob_size)
645			clear_slots(base, self);
646		base = base->tp_base;
647		assert(base);
648	}
649
650	/* If we added a dict, DECREF it */
651	if (type->tp_dictoffset && !base->tp_dictoffset) {
652		PyObject **dictptr = _PyObject_GetDictPtr(self);
653		if (dictptr != NULL) {
654			PyObject *dict = *dictptr;
655			if (dict != NULL) {
656				Py_DECREF(dict);
657				*dictptr = NULL;
658			}
659		}
660	}
661
662	/* If we added weaklist, we clear it */
663	if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
664		PyObject_ClearWeakRefs(self);
665
666	/* Finalize GC if the base doesn't do GC and we do */
667	if (!PyType_IS_GC(base))
668		_PyObject_GC_UNTRACK(self);
669
670	/* Call the base tp_dealloc() */
671	assert(basedealloc);
672	basedealloc(self);
673
674	/* Can't reference self beyond this point */
675	Py_DECREF(type);
676
677  endlabel:
678	++_PyTrash_delete_nesting;
679	Py_TRASHCAN_SAFE_END(self);
680	--_PyTrash_delete_nesting;
681
682	/* Explanation of the weirdness around the trashcan macros:
683
684	   Q. What do the trashcan macros do?
685
686	   A. Read the comment titled "Trashcan mechanism" in object.h.
687	      For one, this explains why there must be a call to GC-untrack
688	      before the trashcan begin macro.  Without understanding the
689	      trashcan code, the answers to the following questions don't make
690	      sense.
691
692	   Q. Why do we GC-untrack before the trashcan and then immediately
693	      GC-track again afterward?
694
695	   A. In the case that the base class is GC-aware, the base class
696	      probably GC-untracks the object.  If it does that using the
697	      UNTRACK macro, this will crash when the object is already
698	      untracked.  Because we don't know what the base class does, the
699	      only safe thing is to make sure the object is tracked when we
700	      call the base class dealloc.  But...  The trashcan begin macro
701	      requires that the object is *untracked* before it is called.  So
702	      the dance becomes:
703
704	         GC untrack
705		 trashcan begin
706		 GC track
707
708	   Q. Why the bizarre (net-zero) manipulation of
709	      _PyTrash_delete_nesting around the trashcan macros?
710
711	   A. Some base classes (e.g. list) also use the trashcan mechanism.
712	      The following scenario used to be possible:
713
714	      - suppose the trashcan level is one below the trashcan limit
715
716	      - subtype_dealloc() is called
717
718	      - the trashcan limit is not yet reached, so the trashcan level
719	        is incremented and the code between trashcan begin and end is
720	        executed
721
722	      - this destroys much of the object's contents, including its
723	        slots and __dict__
724
725	      - basedealloc() is called; this is really list_dealloc(), or
726	        some other type which also uses the trashcan macros
727
728	      - the trashcan limit is now reached, so the object is put on the
729	        trashcan's to-be-deleted-later list
730
731	      - basedealloc() returns
732
733	      - subtype_dealloc() decrefs the object's type
734
735	      - subtype_dealloc() returns
736
737	      - later, the trashcan code starts deleting the objects from its
738	        to-be-deleted-later list
739
740	      - subtype_dealloc() is called *AGAIN* for the same object
741
742	      - at the very least (if the destroyed slots and __dict__ don't
743	        cause problems) the object's type gets decref'ed a second
744	        time, which is *BAD*!!!
745
746	      The remedy is to make sure that if the code between trashcan
747	      begin and end in subtype_dealloc() is called, the code between
748	      trashcan begin and end in basedealloc() will also be called.
749	      This is done by decrementing the level after passing into the
750	      trashcan block, and incrementing it just before leaving the
751	      block.
752
753	      But now it's possible that a chain of objects consisting solely
754	      of objects whose deallocator is subtype_dealloc() will defeat
755	      the trashcan mechanism completely: the decremented level means
756	      that the effective level never reaches the limit.  Therefore, we
757	      *increment* the level *before* entering the trashcan block, and
758	      matchingly decrement it after leaving.  This means the trashcan
759	      code will trigger a little early, but that's no big deal.
760
761	   Q. Are there any live examples of code in need of all this
762	      complexity?
763
764	   A. Yes.  See SF bug 668433 for code that crashed (when Python was
765	      compiled in debug mode) before the trashcan level manipulations
766	      were added.  For more discussion, see SF patches 581742, 575073
767	      and bug 574207.
768	*/
769}
770
771static PyTypeObject *solid_base(PyTypeObject *type);
772
773/* type test with subclassing support */
774
775int
776PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
777{
778	PyObject *mro;
779
780	if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
781		return b == a || b == &PyBaseObject_Type;
782
783	mro = a->tp_mro;
784	if (mro != NULL) {
785		/* Deal with multiple inheritance without recursion
786		   by walking the MRO tuple */
787		int i, n;
788		assert(PyTuple_Check(mro));
789		n = PyTuple_GET_SIZE(mro);
790		for (i = 0; i < n; i++) {
791			if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
792				return 1;
793		}
794		return 0;
795	}
796	else {
797		/* a is not completely initilized yet; follow tp_base */
798		do {
799			if (a == b)
800				return 1;
801			a = a->tp_base;
802		} while (a != NULL);
803		return b == &PyBaseObject_Type;
804	}
805}
806
807/* Internal routines to do a method lookup in the type
808   without looking in the instance dictionary
809   (so we can't use PyObject_GetAttr) but still binding
810   it to the instance.  The arguments are the object,
811   the method name as a C string, and the address of a
812   static variable used to cache the interned Python string.
813
814   Two variants:
815
816   - lookup_maybe() returns NULL without raising an exception
817     when the _PyType_Lookup() call fails;
818
819   - lookup_method() always raises an exception upon errors.
820*/
821
822static PyObject *
823lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
824{
825	PyObject *res;
826
827	if (*attrobj == NULL) {
828		*attrobj = PyString_InternFromString(attrstr);
829		if (*attrobj == NULL)
830			return NULL;
831	}
832	res = _PyType_Lookup(self->ob_type, *attrobj);
833	if (res != NULL) {
834		descrgetfunc f;
835		if ((f = res->ob_type->tp_descr_get) == NULL)
836			Py_INCREF(res);
837		else
838			res = f(res, self, (PyObject *)(self->ob_type));
839	}
840	return res;
841}
842
843static PyObject *
844lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
845{
846	PyObject *res = lookup_maybe(self, attrstr, attrobj);
847	if (res == NULL && !PyErr_Occurred())
848		PyErr_SetObject(PyExc_AttributeError, *attrobj);
849	return res;
850}
851
852/* A variation of PyObject_CallMethod that uses lookup_method()
853   instead of PyObject_GetAttrString().  This uses the same convention
854   as lookup_method to cache the interned name string object. */
855
856static PyObject *
857call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
858{
859	va_list va;
860	PyObject *args, *func = 0, *retval;
861	va_start(va, format);
862
863	func = lookup_maybe(o, name, nameobj);
864	if (func == NULL) {
865		va_end(va);
866		if (!PyErr_Occurred())
867			PyErr_SetObject(PyExc_AttributeError, *nameobj);
868		return NULL;
869	}
870
871	if (format && *format)
872		args = Py_VaBuildValue(format, va);
873	else
874		args = PyTuple_New(0);
875
876	va_end(va);
877
878	if (args == NULL)
879		return NULL;
880
881	assert(PyTuple_Check(args));
882	retval = PyObject_Call(func, args, NULL);
883
884	Py_DECREF(args);
885	Py_DECREF(func);
886
887	return retval;
888}
889
890/* Clone of call_method() that returns NotImplemented when the lookup fails. */
891
892static PyObject *
893call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
894{
895	va_list va;
896	PyObject *args, *func = 0, *retval;
897	va_start(va, format);
898
899	func = lookup_maybe(o, name, nameobj);
900	if (func == NULL) {
901		va_end(va);
902		if (!PyErr_Occurred()) {
903			Py_INCREF(Py_NotImplemented);
904			return Py_NotImplemented;
905		}
906		return NULL;
907	}
908
909	if (format && *format)
910		args = Py_VaBuildValue(format, va);
911	else
912		args = PyTuple_New(0);
913
914	va_end(va);
915
916	if (args == NULL)
917		return NULL;
918
919	assert(PyTuple_Check(args));
920	retval = PyObject_Call(func, args, NULL);
921
922	Py_DECREF(args);
923	Py_DECREF(func);
924
925	return retval;
926}
927
928static int
929fill_classic_mro(PyObject *mro, PyObject *cls)
930{
931	PyObject *bases, *base;
932	int i, n;
933
934	assert(PyList_Check(mro));
935	assert(PyClass_Check(cls));
936	i = PySequence_Contains(mro, cls);
937	if (i < 0)
938		return -1;
939	if (!i) {
940		if (PyList_Append(mro, cls) < 0)
941			return -1;
942	}
943	bases = ((PyClassObject *)cls)->cl_bases;
944	assert(bases && PyTuple_Check(bases));
945	n = PyTuple_GET_SIZE(bases);
946	for (i = 0; i < n; i++) {
947		base = PyTuple_GET_ITEM(bases, i);
948		if (fill_classic_mro(mro, base) < 0)
949			return -1;
950	}
951	return 0;
952}
953
954static PyObject *
955classic_mro(PyObject *cls)
956{
957	PyObject *mro;
958
959	assert(PyClass_Check(cls));
960	mro = PyList_New(0);
961	if (mro != NULL) {
962		if (fill_classic_mro(mro, cls) == 0)
963			return mro;
964		Py_DECREF(mro);
965	}
966	return NULL;
967}
968
969/*
970    Method resolution order algorithm C3 described in
971    "A Monotonic Superclass Linearization for Dylan",
972    by Kim Barrett, Bob Cassel, Paul Haahr,
973    David A. Moon, Keith Playford, and P. Tucker Withington.
974    (OOPSLA 1996)
975
976    Some notes about the rules implied by C3:
977
978    No duplicate bases.
979    It isn't legal to repeat a class in a list of base classes.
980
981    The next three properties are the 3 constraints in "C3".
982
983    Local precendece order.
984    If A precedes B in C's MRO, then A will precede B in the MRO of all
985    subclasses of C.
986
987    Monotonicity.
988    The MRO of a class must be an extension without reordering of the
989    MRO of each of its superclasses.
990
991    Extended Precedence Graph (EPG).
992    Linearization is consistent if there is a path in the EPG from
993    each class to all its successors in the linearization.  See
994    the paper for definition of EPG.
995 */
996
997static int
998tail_contains(PyObject *list, int whence, PyObject *o) {
999	int j, size;
1000	size = PyList_GET_SIZE(list);
1001
1002	for (j = whence+1; j < size; j++) {
1003		if (PyList_GET_ITEM(list, j) == o)
1004			return 1;
1005	}
1006	return 0;
1007}
1008
1009static PyObject *
1010class_name(PyObject *cls)
1011{
1012	PyObject *name = PyObject_GetAttrString(cls, "__name__");
1013	if (name == NULL) {
1014		PyErr_Clear();
1015		Py_XDECREF(name);
1016		name = PyObject_Repr(cls);
1017	}
1018	if (name == NULL)
1019		return NULL;
1020	if (!PyString_Check(name)) {
1021		Py_DECREF(name);
1022		return NULL;
1023	}
1024	return name;
1025}
1026
1027static int
1028check_duplicates(PyObject *list)
1029{
1030	int i, j, n;
1031	/* Let's use a quadratic time algorithm,
1032	   assuming that the bases lists is short.
1033	*/
1034	n = PyList_GET_SIZE(list);
1035	for (i = 0; i < n; i++) {
1036		PyObject *o = PyList_GET_ITEM(list, i);
1037		for (j = i + 1; j < n; j++) {
1038			if (PyList_GET_ITEM(list, j) == o) {
1039				o = class_name(o);
1040				PyErr_Format(PyExc_TypeError,
1041					     "duplicate base class %s",
1042					     o ? PyString_AS_STRING(o) : "?");
1043				Py_XDECREF(o);
1044				return -1;
1045			}
1046		}
1047	}
1048	return 0;
1049}
1050
1051/* Raise a TypeError for an MRO order disagreement.
1052
1053   It's hard to produce a good error message.  In the absence of better
1054   insight into error reporting, report the classes that were candidates
1055   to be put next into the MRO.  There is some conflict between the
1056   order in which they should be put in the MRO, but it's hard to
1057   diagnose what constraint can't be satisfied.
1058*/
1059
1060static void
1061set_mro_error(PyObject *to_merge, int *remain)
1062{
1063	int i, n, off, to_merge_size;
1064	char buf[1000];
1065	PyObject *k, *v;
1066	PyObject *set = PyDict_New();
1067
1068	to_merge_size = PyList_GET_SIZE(to_merge);
1069	for (i = 0; i < to_merge_size; i++) {
1070		PyObject *L = PyList_GET_ITEM(to_merge, i);
1071		if (remain[i] < PyList_GET_SIZE(L)) {
1072			PyObject *c = PyList_GET_ITEM(L, remain[i]);
1073			if (PyDict_SetItem(set, c, Py_None) < 0)
1074				return;
1075		}
1076	}
1077	n = PyDict_Size(set);
1078
1079	off = PyOS_snprintf(buf, sizeof(buf), "Cannot create class.\
1080The superclasses have conflicting\n\
1081inheritance trees which leave the method resolution order (MRO)\n\
1082undefined for bases");
1083	i = 0;
1084	while (PyDict_Next(set, &i, &k, &v) && off < sizeof(buf)) {
1085		PyObject *name = class_name(k);
1086		off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
1087				     name ? PyString_AS_STRING(name) : "?");
1088		Py_XDECREF(name);
1089		if (--n && off+1 < sizeof(buf)) {
1090			buf[off++] = ',';
1091			buf[off] = '\0';
1092		}
1093	}
1094	PyErr_SetString(PyExc_TypeError, buf);
1095	Py_DECREF(set);
1096}
1097
1098static int
1099pmerge(PyObject *acc, PyObject* to_merge) {
1100	int i, j, to_merge_size;
1101	int *remain;
1102	int ok, empty_cnt;
1103
1104	to_merge_size = PyList_GET_SIZE(to_merge);
1105
1106	/* remain stores an index into each sublist of to_merge.
1107	   remain[i] is the index of the next base in to_merge[i]
1108	   that is not included in acc.
1109	*/
1110	remain = PyMem_MALLOC(SIZEOF_INT*to_merge_size);
1111	if (remain == NULL)
1112		return -1;
1113	for (i = 0; i < to_merge_size; i++)
1114		remain[i] = 0;
1115
1116  again:
1117	empty_cnt = 0;
1118	for (i = 0; i < to_merge_size; i++) {
1119		PyObject *candidate;
1120
1121		PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
1122
1123		if (remain[i] >= PyList_GET_SIZE(cur_list)) {
1124			empty_cnt++;
1125			continue;
1126                }
1127
1128		/* Choose next candidate for MRO.
1129
1130		   The input sequences alone can determine the choice.
1131		   If not, choose the class which appears in the MRO
1132		   of the earliest direct superclass of the new class.
1133		*/
1134
1135		candidate = PyList_GET_ITEM(cur_list, remain[i]);
1136		for (j = 0; j < to_merge_size; j++) {
1137			PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1138			if (tail_contains(j_lst, remain[j], candidate)) {
1139				goto skip; /* continue outer loop */
1140			}
1141		}
1142		ok = PyList_Append(acc, candidate);
1143		if (ok < 0) {
1144			PyMem_Free(remain);
1145			return -1;
1146		}
1147		for (j = 0; j < to_merge_size; j++) {
1148			PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
1149			if (remain[j] < PyList_GET_SIZE(j_lst) &&
1150			    PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
1151				remain[j]++;
1152			}
1153		}
1154		goto again;
1155	  skip: ;
1156	}
1157
1158	if (empty_cnt == to_merge_size) {
1159		PyMem_FREE(remain);
1160		return 0;
1161	}
1162	set_mro_error(to_merge, remain);
1163	PyMem_FREE(remain);
1164	return -1;
1165}
1166
1167static PyObject *
1168mro_implementation(PyTypeObject *type)
1169{
1170	int i, n, ok;
1171	PyObject *bases, *result;
1172	PyObject *to_merge, *bases_aslist;
1173
1174	if(type->tp_dict == NULL) {
1175		if(PyType_Ready(type) < 0)
1176			return NULL;
1177	}
1178
1179	/* Find a superclass linearization that honors the constraints
1180	   of the explicit lists of bases and the constraints implied by
1181	   each base class.
1182
1183	   to_merge is a list of lists, where each list is a superclass
1184	   linearization implied by a base class.  The last element of
1185	   to_merge is the declared list of bases.
1186	*/
1187
1188	bases = type->tp_bases;
1189	n = PyTuple_GET_SIZE(bases);
1190
1191	to_merge = PyList_New(n+1);
1192	if (to_merge == NULL)
1193		return NULL;
1194
1195	for (i = 0; i < n; i++) {
1196		PyObject *base = PyTuple_GET_ITEM(bases, i);
1197		PyObject *parentMRO;
1198		if (PyType_Check(base))
1199			parentMRO = PySequence_List(
1200				((PyTypeObject*)base)->tp_mro);
1201		else
1202			parentMRO = classic_mro(base);
1203		if (parentMRO == NULL) {
1204			Py_DECREF(to_merge);
1205			return NULL;
1206	        }
1207
1208		PyList_SET_ITEM(to_merge, i, parentMRO);
1209	}
1210
1211	bases_aslist = PySequence_List(bases);
1212	if (bases_aslist == NULL) {
1213		Py_DECREF(to_merge);
1214		return NULL;
1215	}
1216	/* This is just a basic sanity check. */
1217	if (check_duplicates(bases_aslist) < 0) {
1218		Py_DECREF(to_merge);
1219		Py_DECREF(bases_aslist);
1220		return NULL;
1221	}
1222	PyList_SET_ITEM(to_merge, n, bases_aslist);
1223
1224	result = Py_BuildValue("[O]", (PyObject *)type);
1225	if (result == NULL) {
1226		Py_DECREF(to_merge);
1227		return NULL;
1228	}
1229
1230	ok = pmerge(result, to_merge);
1231	Py_DECREF(to_merge);
1232	if (ok < 0) {
1233		Py_DECREF(result);
1234		return NULL;
1235	}
1236
1237	return result;
1238}
1239
1240static PyObject *
1241mro_external(PyObject *self)
1242{
1243	PyTypeObject *type = (PyTypeObject *)self;
1244
1245	return mro_implementation(type);
1246}
1247
1248static int
1249mro_internal(PyTypeObject *type)
1250{
1251	PyObject *mro, *result, *tuple;
1252
1253	if (type->ob_type == &PyType_Type) {
1254		result = mro_implementation(type);
1255	}
1256	else {
1257		static PyObject *mro_str;
1258		mro = lookup_method((PyObject *)type, "mro", &mro_str);
1259		if (mro == NULL)
1260			return -1;
1261		result = PyObject_CallObject(mro, NULL);
1262		Py_DECREF(mro);
1263	}
1264	if (result == NULL)
1265		return -1;
1266	tuple = PySequence_Tuple(result);
1267	Py_DECREF(result);
1268	type->tp_mro = tuple;
1269	return 0;
1270}
1271
1272
1273/* Calculate the best base amongst multiple base classes.
1274   This is the first one that's on the path to the "solid base". */
1275
1276static PyTypeObject *
1277best_base(PyObject *bases)
1278{
1279	int i, n;
1280	PyTypeObject *base, *winner, *candidate, *base_i;
1281	PyObject *base_proto;
1282
1283	assert(PyTuple_Check(bases));
1284	n = PyTuple_GET_SIZE(bases);
1285	assert(n > 0);
1286	base = NULL;
1287	winner = NULL;
1288	for (i = 0; i < n; i++) {
1289		base_proto = PyTuple_GET_ITEM(bases, i);
1290		if (PyClass_Check(base_proto))
1291			continue;
1292		if (!PyType_Check(base_proto)) {
1293			PyErr_SetString(
1294				PyExc_TypeError,
1295				"bases must be types");
1296			return NULL;
1297		}
1298		base_i = (PyTypeObject *)base_proto;
1299		if (base_i->tp_dict == NULL) {
1300			if (PyType_Ready(base_i) < 0)
1301				return NULL;
1302		}
1303		candidate = solid_base(base_i);
1304		if (winner == NULL) {
1305			winner = candidate;
1306			base = base_i;
1307		}
1308		else if (PyType_IsSubtype(winner, candidate))
1309			;
1310		else if (PyType_IsSubtype(candidate, winner)) {
1311			winner = candidate;
1312			base = base_i;
1313		}
1314		else {
1315			PyErr_SetString(
1316				PyExc_TypeError,
1317				"multiple bases have "
1318				"instance lay-out conflict");
1319			return NULL;
1320		}
1321	}
1322	if (base == NULL)
1323		PyErr_SetString(PyExc_TypeError,
1324			"a new-style class can't have only classic bases");
1325	return base;
1326}
1327
1328static int
1329extra_ivars(PyTypeObject *type, PyTypeObject *base)
1330{
1331	size_t t_size = type->tp_basicsize;
1332	size_t b_size = base->tp_basicsize;
1333
1334	assert(t_size >= b_size); /* Else type smaller than base! */
1335	if (type->tp_itemsize || base->tp_itemsize) {
1336		/* If itemsize is involved, stricter rules */
1337		return t_size != b_size ||
1338			type->tp_itemsize != base->tp_itemsize;
1339	}
1340	if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
1341	    type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
1342		t_size -= sizeof(PyObject *);
1343	if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
1344	    type->tp_dictoffset + sizeof(PyObject *) == t_size)
1345		t_size -= sizeof(PyObject *);
1346
1347	return t_size != b_size;
1348}
1349
1350static PyTypeObject *
1351solid_base(PyTypeObject *type)
1352{
1353	PyTypeObject *base;
1354
1355	if (type->tp_base)
1356		base = solid_base(type->tp_base);
1357	else
1358		base = &PyBaseObject_Type;
1359	if (extra_ivars(type, base))
1360		return type;
1361	else
1362		return base;
1363}
1364
1365static void object_dealloc(PyObject *);
1366static int object_init(PyObject *, PyObject *, PyObject *);
1367static int update_slot(PyTypeObject *, PyObject *);
1368static void fixup_slot_dispatchers(PyTypeObject *);
1369
1370static PyObject *
1371subtype_dict(PyObject *obj, void *context)
1372{
1373	PyObject **dictptr = _PyObject_GetDictPtr(obj);
1374	PyObject *dict;
1375
1376	if (dictptr == NULL) {
1377		PyErr_SetString(PyExc_AttributeError,
1378				"This object has no __dict__");
1379		return NULL;
1380	}
1381	dict = *dictptr;
1382	if (dict == NULL)
1383		*dictptr = dict = PyDict_New();
1384	Py_XINCREF(dict);
1385	return dict;
1386}
1387
1388static int
1389subtype_setdict(PyObject *obj, PyObject *value, void *context)
1390{
1391	PyObject **dictptr = _PyObject_GetDictPtr(obj);
1392	PyObject *dict;
1393
1394	if (dictptr == NULL) {
1395		PyErr_SetString(PyExc_AttributeError,
1396				"This object has no __dict__");
1397		return -1;
1398	}
1399	if (value != NULL && !PyDict_Check(value)) {
1400		PyErr_SetString(PyExc_TypeError,
1401				"__dict__ must be set to a dictionary");
1402		return -1;
1403	}
1404	dict = *dictptr;
1405	Py_XINCREF(value);
1406	*dictptr = value;
1407	Py_XDECREF(dict);
1408	return 0;
1409}
1410
1411static PyObject *
1412subtype_getweakref(PyObject *obj, void *context)
1413{
1414	PyObject **weaklistptr;
1415	PyObject *result;
1416
1417	if (obj->ob_type->tp_weaklistoffset == 0) {
1418		PyErr_SetString(PyExc_AttributeError,
1419				"This object has no __weaklist__");
1420		return NULL;
1421	}
1422	assert(obj->ob_type->tp_weaklistoffset > 0);
1423	assert(obj->ob_type->tp_weaklistoffset + sizeof(PyObject *) <=
1424	       (size_t)(obj->ob_type->tp_basicsize));
1425	weaklistptr = (PyObject **)
1426		((char *)obj + obj->ob_type->tp_weaklistoffset);
1427	if (*weaklistptr == NULL)
1428		result = Py_None;
1429	else
1430		result = *weaklistptr;
1431	Py_INCREF(result);
1432	return result;
1433}
1434
1435/* Three variants on the subtype_getsets list. */
1436
1437static PyGetSetDef subtype_getsets_full[] = {
1438	{"__dict__", subtype_dict, subtype_setdict,
1439	 PyDoc_STR("dictionary for instance variables (if defined)")},
1440	{"__weakref__", subtype_getweakref, NULL,
1441	 PyDoc_STR("list of weak references to the object (if defined)")},
1442	{0}
1443};
1444
1445static PyGetSetDef subtype_getsets_dict_only[] = {
1446	{"__dict__", subtype_dict, subtype_setdict,
1447	 PyDoc_STR("dictionary for instance variables (if defined)")},
1448	{0}
1449};
1450
1451static PyGetSetDef subtype_getsets_weakref_only[] = {
1452	{"__weakref__", subtype_getweakref, NULL,
1453	 PyDoc_STR("list of weak references to the object (if defined)")},
1454	{0}
1455};
1456
1457static int
1458valid_identifier(PyObject *s)
1459{
1460	unsigned char *p;
1461	int i, n;
1462
1463	if (!PyString_Check(s)) {
1464		PyErr_SetString(PyExc_TypeError,
1465				"__slots__ must be strings");
1466		return 0;
1467	}
1468	p = (unsigned char *) PyString_AS_STRING(s);
1469	n = PyString_GET_SIZE(s);
1470	/* We must reject an empty name.  As a hack, we bump the
1471	   length to 1 so that the loop will balk on the trailing \0. */
1472	if (n == 0)
1473		n = 1;
1474	for (i = 0; i < n; i++, p++) {
1475		if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
1476			PyErr_SetString(PyExc_TypeError,
1477					"__slots__ must be identifiers");
1478			return 0;
1479		}
1480	}
1481	return 1;
1482}
1483
1484#ifdef Py_USING_UNICODE
1485/* Replace Unicode objects in slots.  */
1486
1487static PyObject *
1488_unicode_to_string(PyObject *slots, int nslots)
1489{
1490	PyObject *tmp = slots;
1491	PyObject *o, *o1;
1492	int i;
1493	intintargfunc copy = slots->ob_type->tp_as_sequence->sq_slice;
1494	for (i = 0; i < nslots; i++) {
1495		if (PyUnicode_Check(o = PyTuple_GET_ITEM(tmp, i))) {
1496			if (tmp == slots) {
1497				tmp = copy(slots, 0, PyTuple_GET_SIZE(slots));
1498				if (tmp == NULL)
1499					return NULL;
1500			}
1501			o1 = _PyUnicode_AsDefaultEncodedString
1502					(o, NULL);
1503			if (o1 == NULL) {
1504				Py_DECREF(tmp);
1505				return 0;
1506			}
1507			Py_INCREF(o1);
1508			Py_DECREF(o);
1509			PyTuple_SET_ITEM(tmp, i, o1);
1510		}
1511	}
1512	return tmp;
1513}
1514#endif
1515
1516static PyObject *
1517type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
1518{
1519	PyObject *name, *bases, *dict;
1520	static char *kwlist[] = {"name", "bases", "dict", 0};
1521	PyObject *slots, *tmp, *newslots;
1522	PyTypeObject *type, *base, *tmptype, *winner;
1523	PyHeapTypeObject *et;
1524	PyMemberDef *mp;
1525	int i, nbases, nslots, slotoffset, add_dict, add_weak;
1526	int j, may_add_dict, may_add_weak;
1527
1528	assert(args != NULL && PyTuple_Check(args));
1529	assert(kwds == NULL || PyDict_Check(kwds));
1530
1531	/* Special case: type(x) should return x->ob_type */
1532	{
1533		const int nargs = PyTuple_GET_SIZE(args);
1534		const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
1535
1536		if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
1537			PyObject *x = PyTuple_GET_ITEM(args, 0);
1538			Py_INCREF(x->ob_type);
1539			return (PyObject *) x->ob_type;
1540		}
1541
1542		/* SF bug 475327 -- if that didn't trigger, we need 3
1543		   arguments. but PyArg_ParseTupleAndKeywords below may give
1544		   a msg saying type() needs exactly 3. */
1545		if (nargs + nkwds != 3) {
1546			PyErr_SetString(PyExc_TypeError,
1547					"type() takes 1 or 3 arguments");
1548			return NULL;
1549		}
1550	}
1551
1552	/* Check arguments: (name, bases, dict) */
1553	if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
1554					 &name,
1555					 &PyTuple_Type, &bases,
1556					 &PyDict_Type, &dict))
1557		return NULL;
1558
1559	/* Determine the proper metatype to deal with this,
1560	   and check for metatype conflicts while we're at it.
1561	   Note that if some other metatype wins to contract,
1562	   it's possible that its instances are not types. */
1563	nbases = PyTuple_GET_SIZE(bases);
1564	winner = metatype;
1565	for (i = 0; i < nbases; i++) {
1566		tmp = PyTuple_GET_ITEM(bases, i);
1567		tmptype = tmp->ob_type;
1568		if (tmptype == &PyClass_Type)
1569			continue; /* Special case classic classes */
1570		if (PyType_IsSubtype(winner, tmptype))
1571			continue;
1572		if (PyType_IsSubtype(tmptype, winner)) {
1573			winner = tmptype;
1574			continue;
1575		}
1576		PyErr_SetString(PyExc_TypeError,
1577				"metatype conflict among bases");
1578		return NULL;
1579	}
1580	if (winner != metatype) {
1581		if (winner->tp_new != type_new) /* Pass it to the winner */
1582			return winner->tp_new(winner, args, kwds);
1583		metatype = winner;
1584	}
1585
1586	/* Adjust for empty tuple bases */
1587	if (nbases == 0) {
1588		bases = Py_BuildValue("(O)", &PyBaseObject_Type);
1589		if (bases == NULL)
1590			return NULL;
1591		nbases = 1;
1592	}
1593	else
1594		Py_INCREF(bases);
1595
1596	/* XXX From here until type is allocated, "return NULL" leaks bases! */
1597
1598	/* Calculate best base, and check that all bases are type objects */
1599	base = best_base(bases);
1600	if (base == NULL)
1601		return NULL;
1602	if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
1603		PyErr_Format(PyExc_TypeError,
1604			     "type '%.100s' is not an acceptable base type",
1605			     base->tp_name);
1606		return NULL;
1607	}
1608
1609	/* Check for a __slots__ sequence variable in dict, and count it */
1610	slots = PyDict_GetItemString(dict, "__slots__");
1611	nslots = 0;
1612	add_dict = 0;
1613	add_weak = 0;
1614	may_add_dict = base->tp_dictoffset == 0;
1615	may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
1616	if (slots == NULL) {
1617		if (may_add_dict) {
1618			add_dict++;
1619		}
1620		if (may_add_weak) {
1621			add_weak++;
1622		}
1623	}
1624	else {
1625		/* Have slots */
1626
1627		/* Make it into a tuple */
1628		if (PyString_Check(slots))
1629			slots = Py_BuildValue("(O)", slots);
1630		else
1631			slots = PySequence_Tuple(slots);
1632		if (slots == NULL)
1633			return NULL;
1634		assert(PyTuple_Check(slots));
1635
1636		/* Are slots allowed? */
1637		nslots = PyTuple_GET_SIZE(slots);
1638		if (nslots > 0 && base->tp_itemsize != 0 && !PyType_Check(base)) {
1639			/* for the special case of meta types, allow slots */
1640			PyErr_Format(PyExc_TypeError,
1641				     "nonempty __slots__ "
1642				     "not supported for subtype of '%s'",
1643				     base->tp_name);
1644		  bad_slots:
1645			Py_DECREF(slots);
1646			return NULL;
1647		}
1648
1649#ifdef Py_USING_UNICODE
1650		tmp = _unicode_to_string(slots, nslots);
1651		if (tmp != slots) {
1652			Py_DECREF(slots);
1653			slots = tmp;
1654		}
1655		if (!tmp)
1656			return NULL;
1657#endif
1658		/* Check for valid slot names and two special cases */
1659		for (i = 0; i < nslots; i++) {
1660			PyObject *tmp = PyTuple_GET_ITEM(slots, i);
1661			char *s;
1662			if (!valid_identifier(tmp))
1663				goto bad_slots;
1664			assert(PyString_Check(tmp));
1665			s = PyString_AS_STRING(tmp);
1666			if (strcmp(s, "__dict__") == 0) {
1667				if (!may_add_dict || add_dict) {
1668					PyErr_SetString(PyExc_TypeError,
1669						"__dict__ slot disallowed: "
1670						"we already got one");
1671					goto bad_slots;
1672				}
1673				add_dict++;
1674			}
1675			if (strcmp(s, "__weakref__") == 0) {
1676				if (!may_add_weak || add_weak) {
1677					PyErr_SetString(PyExc_TypeError,
1678						"__weakref__ slot disallowed: "
1679						"either we already got one, "
1680						"or __itemsize__ != 0");
1681					goto bad_slots;
1682				}
1683				add_weak++;
1684			}
1685		}
1686
1687		/* Copy slots into yet another tuple, demangling names */
1688		newslots = PyTuple_New(nslots - add_dict - add_weak);
1689		if (newslots == NULL)
1690			goto bad_slots;
1691		for (i = j = 0; i < nslots; i++) {
1692			char *s;
1693			char buffer[256];
1694			tmp = PyTuple_GET_ITEM(slots, i);
1695			s = PyString_AS_STRING(tmp);
1696			if ((add_dict && strcmp(s, "__dict__") == 0) ||
1697			    (add_weak && strcmp(s, "__weakref__") == 0))
1698				continue;
1699			if (_Py_Mangle(PyString_AS_STRING(name),
1700				       PyString_AS_STRING(tmp),
1701				       buffer, sizeof(buffer)))
1702			{
1703				tmp = PyString_FromString(buffer);
1704			} else {
1705				Py_INCREF(tmp);
1706			}
1707			PyTuple_SET_ITEM(newslots, j, tmp);
1708			j++;
1709		}
1710		assert(j == nslots - add_dict - add_weak);
1711		nslots = j;
1712		Py_DECREF(slots);
1713		slots = newslots;
1714
1715		/* Secondary bases may provide weakrefs or dict */
1716		if (nbases > 1 &&
1717		    ((may_add_dict && !add_dict) ||
1718		     (may_add_weak && !add_weak))) {
1719			for (i = 0; i < nbases; i++) {
1720				tmp = PyTuple_GET_ITEM(bases, i);
1721				if (tmp == (PyObject *)base)
1722					continue; /* Skip primary base */
1723				if (PyClass_Check(tmp)) {
1724					/* Classic base class provides both */
1725					if (may_add_dict && !add_dict)
1726						add_dict++;
1727					if (may_add_weak && !add_weak)
1728						add_weak++;
1729					break;
1730				}
1731				assert(PyType_Check(tmp));
1732				tmptype = (PyTypeObject *)tmp;
1733				if (may_add_dict && !add_dict &&
1734				    tmptype->tp_dictoffset != 0)
1735					add_dict++;
1736				if (may_add_weak && !add_weak &&
1737				    tmptype->tp_weaklistoffset != 0)
1738					add_weak++;
1739				if (may_add_dict && !add_dict)
1740					continue;
1741				if (may_add_weak && !add_weak)
1742					continue;
1743				/* Nothing more to check */
1744				break;
1745			}
1746		}
1747	}
1748
1749	/* XXX From here until type is safely allocated,
1750	   "return NULL" may leak slots! */
1751
1752	/* Allocate the type object */
1753	type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
1754	if (type == NULL) {
1755		Py_XDECREF(slots);
1756		return NULL;
1757	}
1758
1759	/* Keep name and slots alive in the extended type object */
1760	et = (PyHeapTypeObject *)type;
1761	Py_INCREF(name);
1762	et->name = name;
1763	et->slots = slots;
1764
1765	/* Initialize tp_flags */
1766	type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
1767		Py_TPFLAGS_BASETYPE;
1768	if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
1769		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1770
1771	/* It's a new-style number unless it specifically inherits any
1772	   old-style numeric behavior */
1773	if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
1774	    (base->tp_as_number == NULL))
1775		type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
1776
1777	/* Initialize essential fields */
1778	type->tp_as_number = &et->as_number;
1779	type->tp_as_sequence = &et->as_sequence;
1780	type->tp_as_mapping = &et->as_mapping;
1781	type->tp_as_buffer = &et->as_buffer;
1782	type->tp_name = PyString_AS_STRING(name);
1783
1784	/* Set tp_base and tp_bases */
1785	type->tp_bases = bases;
1786	Py_INCREF(base);
1787	type->tp_base = base;
1788
1789	/* Initialize tp_dict from passed-in dict */
1790	type->tp_dict = dict = PyDict_Copy(dict);
1791	if (dict == NULL) {
1792		Py_DECREF(type);
1793		return NULL;
1794	}
1795
1796	/* Set __module__ in the dict */
1797	if (PyDict_GetItemString(dict, "__module__") == NULL) {
1798		tmp = PyEval_GetGlobals();
1799		if (tmp != NULL) {
1800			tmp = PyDict_GetItemString(tmp, "__name__");
1801			if (tmp != NULL) {
1802				if (PyDict_SetItemString(dict, "__module__",
1803							 tmp) < 0)
1804					return NULL;
1805			}
1806		}
1807	}
1808
1809	/* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1810	   and is a string.  The __doc__ accessor will first look for tp_doc;
1811	   if that fails, it will still look into __dict__.
1812	*/
1813	{
1814		PyObject *doc = PyDict_GetItemString(dict, "__doc__");
1815		if (doc != NULL && PyString_Check(doc)) {
1816			const size_t n = (size_t)PyString_GET_SIZE(doc);
1817			type->tp_doc = (char *)PyObject_MALLOC(n+1);
1818			if (type->tp_doc == NULL) {
1819				Py_DECREF(type);
1820				return NULL;
1821			}
1822			memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
1823		}
1824	}
1825
1826	/* Special-case __new__: if it's a plain function,
1827	   make it a static function */
1828	tmp = PyDict_GetItemString(dict, "__new__");
1829	if (tmp != NULL && PyFunction_Check(tmp)) {
1830		tmp = PyStaticMethod_New(tmp);
1831		if (tmp == NULL) {
1832			Py_DECREF(type);
1833			return NULL;
1834		}
1835		PyDict_SetItemString(dict, "__new__", tmp);
1836		Py_DECREF(tmp);
1837	}
1838
1839	/* Add descriptors for custom slots from __slots__, or for __dict__ */
1840	mp = PyHeapType_GET_MEMBERS(et);
1841	slotoffset = base->tp_basicsize;
1842	if (slots != NULL) {
1843		for (i = 0; i < nslots; i++, mp++) {
1844			mp->name = PyString_AS_STRING(
1845				PyTuple_GET_ITEM(slots, i));
1846			mp->type = T_OBJECT_EX;
1847			mp->offset = slotoffset;
1848			if (base->tp_weaklistoffset == 0 &&
1849			    strcmp(mp->name, "__weakref__") == 0) {
1850				add_weak++;
1851				mp->type = T_OBJECT;
1852				mp->flags = READONLY;
1853				type->tp_weaklistoffset = slotoffset;
1854			}
1855			slotoffset += sizeof(PyObject *);
1856		}
1857	}
1858	if (add_dict) {
1859		if (base->tp_itemsize)
1860			type->tp_dictoffset = -(long)sizeof(PyObject *);
1861		else
1862			type->tp_dictoffset = slotoffset;
1863		slotoffset += sizeof(PyObject *);
1864	}
1865	if (add_weak) {
1866		assert(!base->tp_itemsize);
1867		type->tp_weaklistoffset = slotoffset;
1868		slotoffset += sizeof(PyObject *);
1869	}
1870	type->tp_basicsize = slotoffset;
1871	type->tp_itemsize = base->tp_itemsize;
1872	type->tp_members = PyHeapType_GET_MEMBERS(et);
1873
1874	if (type->tp_weaklistoffset && type->tp_dictoffset)
1875		type->tp_getset = subtype_getsets_full;
1876	else if (type->tp_weaklistoffset && !type->tp_dictoffset)
1877		type->tp_getset = subtype_getsets_weakref_only;
1878	else if (!type->tp_weaklistoffset && type->tp_dictoffset)
1879		type->tp_getset = subtype_getsets_dict_only;
1880	else
1881		type->tp_getset = NULL;
1882
1883	/* Special case some slots */
1884	if (type->tp_dictoffset != 0 || nslots > 0) {
1885		if (base->tp_getattr == NULL && base->tp_getattro == NULL)
1886			type->tp_getattro = PyObject_GenericGetAttr;
1887		if (base->tp_setattr == NULL && base->tp_setattro == NULL)
1888			type->tp_setattro = PyObject_GenericSetAttr;
1889	}
1890	type->tp_dealloc = subtype_dealloc;
1891
1892	/* Enable GC unless there are really no instance variables possible */
1893	if (!(type->tp_basicsize == sizeof(PyObject) &&
1894	      type->tp_itemsize == 0))
1895		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1896
1897	/* Always override allocation strategy to use regular heap */
1898	type->tp_alloc = PyType_GenericAlloc;
1899	if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1900		type->tp_free = PyObject_GC_Del;
1901		type->tp_traverse = subtype_traverse;
1902		type->tp_clear = subtype_clear;
1903	}
1904	else
1905		type->tp_free = PyObject_Del;
1906
1907	/* Initialize the rest */
1908	if (PyType_Ready(type) < 0) {
1909		Py_DECREF(type);
1910		return NULL;
1911	}
1912
1913	/* Put the proper slots in place */
1914	fixup_slot_dispatchers(type);
1915
1916	return (PyObject *)type;
1917}
1918
1919/* Internal API to look for a name through the MRO.
1920   This returns a borrowed reference, and doesn't set an exception! */
1921PyObject *
1922_PyType_Lookup(PyTypeObject *type, PyObject *name)
1923{
1924	int i, n;
1925	PyObject *mro, *res, *base, *dict;
1926
1927	/* Look in tp_dict of types in MRO */
1928	mro = type->tp_mro;
1929
1930	/* If mro is NULL, the type is either not yet initialized
1931	   by PyType_Ready(), or already cleared by type_clear().
1932	   Either way the safest thing to do is to return NULL. */
1933	if (mro == NULL)
1934		return NULL;
1935
1936	assert(PyTuple_Check(mro));
1937	n = PyTuple_GET_SIZE(mro);
1938	for (i = 0; i < n; i++) {
1939		base = PyTuple_GET_ITEM(mro, i);
1940		if (PyClass_Check(base))
1941			dict = ((PyClassObject *)base)->cl_dict;
1942		else {
1943			assert(PyType_Check(base));
1944			dict = ((PyTypeObject *)base)->tp_dict;
1945		}
1946		assert(dict && PyDict_Check(dict));
1947		res = PyDict_GetItem(dict, name);
1948		if (res != NULL)
1949			return res;
1950	}
1951	return NULL;
1952}
1953
1954/* This is similar to PyObject_GenericGetAttr(),
1955   but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
1956static PyObject *
1957type_getattro(PyTypeObject *type, PyObject *name)
1958{
1959	PyTypeObject *metatype = type->ob_type;
1960	PyObject *meta_attribute, *attribute;
1961	descrgetfunc meta_get;
1962
1963	/* Initialize this type (we'll assume the metatype is initialized) */
1964	if (type->tp_dict == NULL) {
1965		if (PyType_Ready(type) < 0)
1966			return NULL;
1967	}
1968
1969	/* No readable descriptor found yet */
1970	meta_get = NULL;
1971
1972	/* Look for the attribute in the metatype */
1973	meta_attribute = _PyType_Lookup(metatype, name);
1974
1975	if (meta_attribute != NULL) {
1976		meta_get = meta_attribute->ob_type->tp_descr_get;
1977
1978		if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
1979			/* Data descriptors implement tp_descr_set to intercept
1980			 * writes. Assume the attribute is not overridden in
1981			 * type's tp_dict (and bases): call the descriptor now.
1982			 */
1983			return meta_get(meta_attribute, (PyObject *)type,
1984					(PyObject *)metatype);
1985		}
1986	}
1987
1988	/* No data descriptor found on metatype. Look in tp_dict of this
1989	 * type and its bases */
1990	attribute = _PyType_Lookup(type, name);
1991	if (attribute != NULL) {
1992		/* Implement descriptor functionality, if any */
1993		descrgetfunc local_get = attribute->ob_type->tp_descr_get;
1994		if (local_get != NULL) {
1995			/* NULL 2nd argument indicates the descriptor was
1996			 * found on the target object itself (or a base)  */
1997			return local_get(attribute, (PyObject *)NULL,
1998					 (PyObject *)type);
1999		}
2000
2001		Py_INCREF(attribute);
2002		return attribute;
2003	}
2004
2005	/* No attribute found in local __dict__ (or bases): use the
2006	 * descriptor from the metatype, if any */
2007	if (meta_get != NULL)
2008		return meta_get(meta_attribute, (PyObject *)type,
2009				(PyObject *)metatype);
2010
2011	/* If an ordinary attribute was found on the metatype, return it now */
2012	if (meta_attribute != NULL) {
2013		Py_INCREF(meta_attribute);
2014		return meta_attribute;
2015	}
2016
2017	/* Give up */
2018	PyErr_Format(PyExc_AttributeError,
2019			 "type object '%.50s' has no attribute '%.400s'",
2020			 type->tp_name, PyString_AS_STRING(name));
2021	return NULL;
2022}
2023
2024static int
2025type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
2026{
2027	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2028		PyErr_Format(
2029			PyExc_TypeError,
2030			"can't set attributes of built-in/extension type '%s'",
2031			type->tp_name);
2032		return -1;
2033	}
2034	if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
2035		return -1;
2036	return update_slot(type, name);
2037}
2038
2039static void
2040type_dealloc(PyTypeObject *type)
2041{
2042	PyHeapTypeObject *et;
2043
2044	/* Assert this is a heap-allocated type object */
2045	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2046	_PyObject_GC_UNTRACK(type);
2047	PyObject_ClearWeakRefs((PyObject *)type);
2048	et = (PyHeapTypeObject *)type;
2049	Py_XDECREF(type->tp_base);
2050	Py_XDECREF(type->tp_dict);
2051	Py_XDECREF(type->tp_bases);
2052	Py_XDECREF(type->tp_mro);
2053	Py_XDECREF(type->tp_cache);
2054	Py_XDECREF(type->tp_subclasses);
2055	PyObject_Free(type->tp_doc);
2056	Py_XDECREF(et->name);
2057	Py_XDECREF(et->slots);
2058	type->ob_type->tp_free((PyObject *)type);
2059}
2060
2061static PyObject *
2062type_subclasses(PyTypeObject *type, PyObject *args_ignored)
2063{
2064	PyObject *list, *raw, *ref;
2065	int i, n;
2066
2067	list = PyList_New(0);
2068	if (list == NULL)
2069		return NULL;
2070	raw = type->tp_subclasses;
2071	if (raw == NULL)
2072		return list;
2073	assert(PyList_Check(raw));
2074	n = PyList_GET_SIZE(raw);
2075	for (i = 0; i < n; i++) {
2076		ref = PyList_GET_ITEM(raw, i);
2077		assert(PyWeakref_CheckRef(ref));
2078		ref = PyWeakref_GET_OBJECT(ref);
2079		if (ref != Py_None) {
2080			if (PyList_Append(list, ref) < 0) {
2081				Py_DECREF(list);
2082				return NULL;
2083			}
2084		}
2085	}
2086	return list;
2087}
2088
2089static PyMethodDef type_methods[] = {
2090	{"mro", (PyCFunction)mro_external, METH_NOARGS,
2091	 PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
2092	{"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
2093	 PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
2094	{0}
2095};
2096
2097PyDoc_STRVAR(type_doc,
2098"type(object) -> the object's type\n"
2099"type(name, bases, dict) -> a new type");
2100
2101static int
2102type_traverse(PyTypeObject *type, visitproc visit, void *arg)
2103{
2104	int err;
2105
2106	/* Because of type_is_gc(), the collector only calls this
2107	   for heaptypes. */
2108	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2109
2110#define VISIT(SLOT) \
2111	if (SLOT) { \
2112		err = visit((PyObject *)(SLOT), arg); \
2113		if (err) \
2114			return err; \
2115	}
2116
2117	VISIT(type->tp_dict);
2118	VISIT(type->tp_cache);
2119	VISIT(type->tp_mro);
2120	VISIT(type->tp_bases);
2121	VISIT(type->tp_base);
2122
2123	/* There's no need to visit type->tp_subclasses or
2124	   ((PyHeapTypeObject *)type)->slots, because they can't be involved
2125	   in cycles; tp_subclasses is a list of weak references,
2126	   and slots is a tuple of strings. */
2127
2128#undef VISIT
2129
2130	return 0;
2131}
2132
2133static int
2134type_clear(PyTypeObject *type)
2135{
2136	PyObject *tmp;
2137
2138	/* Because of type_is_gc(), the collector only calls this
2139	   for heaptypes. */
2140	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
2141
2142#define CLEAR(SLOT) \
2143	if (SLOT) { \
2144		tmp = (PyObject *)(SLOT); \
2145		SLOT = NULL; \
2146		Py_DECREF(tmp); \
2147	}
2148
2149	/* The only field we need to clear is tp_mro, which is part of a
2150	   hard cycle (its first element is the class itself) that won't
2151	   be broken otherwise (it's a tuple and tuples don't have a
2152	   tp_clear handler).  None of the other fields need to be
2153	   cleared, and here's why:
2154
2155	   tp_dict:
2156	       It is a dict, so the collector will call its tp_clear.
2157
2158	   tp_cache:
2159	       Not used; if it were, it would be a dict.
2160
2161	   tp_bases, tp_base:
2162	       If these are involved in a cycle, there must be at least
2163	       one other, mutable object in the cycle, e.g. a base
2164	       class's dict; the cycle will be broken that way.
2165
2166	   tp_subclasses:
2167	       A list of weak references can't be part of a cycle; and
2168	       lists have their own tp_clear.
2169
2170	   slots (in PyHeapTypeObject):
2171	       A tuple of strings can't be part of a cycle.
2172	*/
2173
2174	CLEAR(type->tp_mro);
2175
2176#undef CLEAR
2177
2178	return 0;
2179}
2180
2181static int
2182type_is_gc(PyTypeObject *type)
2183{
2184	return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
2185}
2186
2187PyTypeObject PyType_Type = {
2188	PyObject_HEAD_INIT(&PyType_Type)
2189	0,					/* ob_size */
2190	"type",					/* tp_name */
2191	sizeof(PyHeapTypeObject),		/* tp_basicsize */
2192	sizeof(PyMemberDef),			/* tp_itemsize */
2193	(destructor)type_dealloc,		/* tp_dealloc */
2194	0,					/* tp_print */
2195	0,			 		/* tp_getattr */
2196	0,					/* tp_setattr */
2197	type_compare,				/* tp_compare */
2198	(reprfunc)type_repr,			/* tp_repr */
2199	0,					/* tp_as_number */
2200	0,					/* tp_as_sequence */
2201	0,					/* tp_as_mapping */
2202	(hashfunc)_Py_HashPointer,		/* tp_hash */
2203	(ternaryfunc)type_call,			/* tp_call */
2204	0,					/* tp_str */
2205	(getattrofunc)type_getattro,		/* tp_getattro */
2206	(setattrofunc)type_setattro,		/* tp_setattro */
2207	0,					/* tp_as_buffer */
2208	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2209		Py_TPFLAGS_BASETYPE,		/* tp_flags */
2210	type_doc,				/* tp_doc */
2211	(traverseproc)type_traverse,		/* tp_traverse */
2212	(inquiry)type_clear,			/* tp_clear */
2213	0,					/* tp_richcompare */
2214	offsetof(PyTypeObject, tp_weaklist),	/* tp_weaklistoffset */
2215	0,					/* tp_iter */
2216	0,					/* tp_iternext */
2217	type_methods,				/* tp_methods */
2218	type_members,				/* tp_members */
2219	type_getsets,				/* tp_getset */
2220	0,					/* tp_base */
2221	0,					/* tp_dict */
2222	0,					/* tp_descr_get */
2223	0,					/* tp_descr_set */
2224	offsetof(PyTypeObject, tp_dict),	/* tp_dictoffset */
2225	0,					/* tp_init */
2226	0,					/* tp_alloc */
2227	type_new,				/* tp_new */
2228	PyObject_GC_Del,        		/* tp_free */
2229	(inquiry)type_is_gc,			/* tp_is_gc */
2230};
2231
2232
2233/* The base type of all types (eventually)... except itself. */
2234
2235static int
2236object_init(PyObject *self, PyObject *args, PyObject *kwds)
2237{
2238	return 0;
2239}
2240
2241/* If we don't have a tp_new for a new-style class, new will use this one.
2242   Therefore this should take no arguments/keywords.  However, this new may
2243   also be inherited by objects that define a tp_init but no tp_new.  These
2244   objects WILL pass argumets to tp_new, because it gets the same args as
2245   tp_init.  So only allow arguments if we aren't using the default init, in
2246   which case we expect init to handle argument parsing. */
2247static PyObject *
2248object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2249{
2250	if (type->tp_init == object_init && (PyTuple_GET_SIZE(args) ||
2251	     (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)))) {
2252		PyErr_SetString(PyExc_TypeError,
2253				"default __new__ takes no parameters");
2254		return NULL;
2255	}
2256	return type->tp_alloc(type, 0);
2257}
2258
2259static void
2260object_dealloc(PyObject *self)
2261{
2262	self->ob_type->tp_free(self);
2263}
2264
2265static PyObject *
2266object_repr(PyObject *self)
2267{
2268	PyTypeObject *type;
2269	PyObject *mod, *name, *rtn;
2270
2271	type = self->ob_type;
2272	mod = type_module(type, NULL);
2273	if (mod == NULL)
2274		PyErr_Clear();
2275	else if (!PyString_Check(mod)) {
2276		Py_DECREF(mod);
2277		mod = NULL;
2278	}
2279	name = type_name(type, NULL);
2280	if (name == NULL)
2281		return NULL;
2282	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
2283		rtn = PyString_FromFormat("<%s.%s object at %p>",
2284					  PyString_AS_STRING(mod),
2285					  PyString_AS_STRING(name),
2286					  self);
2287	else
2288		rtn = PyString_FromFormat("<%s object at %p>",
2289					  type->tp_name, self);
2290	Py_XDECREF(mod);
2291	Py_DECREF(name);
2292	return rtn;
2293}
2294
2295static PyObject *
2296object_str(PyObject *self)
2297{
2298	unaryfunc f;
2299
2300	f = self->ob_type->tp_repr;
2301	if (f == NULL)
2302		f = object_repr;
2303	return f(self);
2304}
2305
2306static long
2307object_hash(PyObject *self)
2308{
2309	return _Py_HashPointer(self);
2310}
2311
2312static PyObject *
2313object_get_class(PyObject *self, void *closure)
2314{
2315	Py_INCREF(self->ob_type);
2316	return (PyObject *)(self->ob_type);
2317}
2318
2319static int
2320equiv_structs(PyTypeObject *a, PyTypeObject *b)
2321{
2322	return a == b ||
2323	       (a != NULL &&
2324		b != NULL &&
2325		a->tp_basicsize == b->tp_basicsize &&
2326		a->tp_itemsize == b->tp_itemsize &&
2327		a->tp_dictoffset == b->tp_dictoffset &&
2328		a->tp_weaklistoffset == b->tp_weaklistoffset &&
2329		((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
2330		 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
2331}
2332
2333static int
2334same_slots_added(PyTypeObject *a, PyTypeObject *b)
2335{
2336	PyTypeObject *base = a->tp_base;
2337	int size;
2338
2339	if (base != b->tp_base)
2340		return 0;
2341	if (equiv_structs(a, base) && equiv_structs(b, base))
2342		return 1;
2343	size = base->tp_basicsize;
2344	if (a->tp_dictoffset == size && b->tp_dictoffset == size)
2345		size += sizeof(PyObject *);
2346	if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
2347		size += sizeof(PyObject *);
2348	return size == a->tp_basicsize && size == b->tp_basicsize;
2349}
2350
2351static int
2352compatible_for_assignment(PyTypeObject* old, PyTypeObject* new, char* attr)
2353{
2354	PyTypeObject *newbase, *oldbase;
2355
2356	if (new->tp_dealloc != old->tp_dealloc ||
2357	    new->tp_free != old->tp_free)
2358	{
2359		PyErr_Format(PyExc_TypeError,
2360			     "%s assignment: "
2361			     "'%s' deallocator differs from '%s'",
2362			     attr,
2363			     new->tp_name,
2364			     old->tp_name);
2365		return 0;
2366	}
2367	newbase = new;
2368	oldbase = old;
2369	while (equiv_structs(newbase, newbase->tp_base))
2370		newbase = newbase->tp_base;
2371	while (equiv_structs(oldbase, oldbase->tp_base))
2372		oldbase = oldbase->tp_base;
2373	if (newbase != oldbase &&
2374	    (newbase->tp_base != oldbase->tp_base ||
2375	     !same_slots_added(newbase, oldbase))) {
2376		PyErr_Format(PyExc_TypeError,
2377			     "%s assignment: "
2378			     "'%s' object layout differs from '%s'",
2379			     attr,
2380			     new->tp_name,
2381			     old->tp_name);
2382		return 0;
2383	}
2384
2385	return 1;
2386}
2387
2388static int
2389object_set_class(PyObject *self, PyObject *value, void *closure)
2390{
2391	PyTypeObject *old = self->ob_type;
2392	PyTypeObject *new;
2393
2394	if (value == NULL) {
2395		PyErr_SetString(PyExc_TypeError,
2396				"can't delete __class__ attribute");
2397		return -1;
2398	}
2399	if (!PyType_Check(value)) {
2400		PyErr_Format(PyExc_TypeError,
2401		  "__class__ must be set to new-style class, not '%s' object",
2402		  value->ob_type->tp_name);
2403		return -1;
2404	}
2405	new = (PyTypeObject *)value;
2406	if (!(new->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
2407	    !(old->tp_flags & Py_TPFLAGS_HEAPTYPE))
2408	{
2409		PyErr_Format(PyExc_TypeError,
2410			     "__class__ assignment: only for heap types");
2411		return -1;
2412	}
2413	if (compatible_for_assignment(new, old, "__class__")) {
2414		Py_INCREF(new);
2415		self->ob_type = new;
2416		Py_DECREF(old);
2417		return 0;
2418	}
2419	else {
2420		return -1;
2421	}
2422}
2423
2424static PyGetSetDef object_getsets[] = {
2425	{"__class__", object_get_class, object_set_class,
2426	 PyDoc_STR("the object's class")},
2427	{0}
2428};
2429
2430
2431/* Stuff to implement __reduce_ex__ for pickle protocols >= 2.
2432   We fall back to helpers in copy_reg for:
2433   - pickle protocols < 2
2434   - calculating the list of slot names (done only once per class)
2435   - the __newobj__ function (which is used as a token but never called)
2436*/
2437
2438static PyObject *
2439import_copy_reg(void)
2440{
2441	static PyObject *copy_reg_str;
2442
2443	if (!copy_reg_str) {
2444		copy_reg_str = PyString_InternFromString("copy_reg");
2445		if (copy_reg_str == NULL)
2446			return NULL;
2447	}
2448
2449	return PyImport_Import(copy_reg_str);
2450}
2451
2452static PyObject *
2453slotnames(PyObject *cls)
2454{
2455	PyObject *clsdict;
2456	PyObject *copy_reg;
2457	PyObject *slotnames;
2458
2459	if (!PyType_Check(cls)) {
2460		Py_INCREF(Py_None);
2461		return Py_None;
2462	}
2463
2464	clsdict = ((PyTypeObject *)cls)->tp_dict;
2465	slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
2466	if (slotnames != NULL) {
2467		Py_INCREF(slotnames);
2468		return slotnames;
2469	}
2470
2471	copy_reg = import_copy_reg();
2472	if (copy_reg == NULL)
2473		return NULL;
2474
2475	slotnames = PyObject_CallMethod(copy_reg, "_slotnames", "O", cls);
2476	Py_DECREF(copy_reg);
2477	if (slotnames != NULL &&
2478	    slotnames != Py_None &&
2479	    !PyList_Check(slotnames))
2480	{
2481		PyErr_SetString(PyExc_TypeError,
2482			"copy_reg._slotnames didn't return a list or None");
2483		Py_DECREF(slotnames);
2484		slotnames = NULL;
2485	}
2486
2487	return slotnames;
2488}
2489
2490static PyObject *
2491reduce_2(PyObject *obj)
2492{
2493	PyObject *cls, *getnewargs;
2494	PyObject *args = NULL, *args2 = NULL;
2495	PyObject *getstate = NULL, *state = NULL, *names = NULL;
2496	PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
2497	PyObject *copy_reg = NULL, *newobj = NULL, *res = NULL;
2498	int i, n;
2499
2500	cls = PyObject_GetAttrString(obj, "__class__");
2501	if (cls == NULL)
2502		return NULL;
2503
2504	getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
2505	if (getnewargs != NULL) {
2506		args = PyObject_CallObject(getnewargs, NULL);
2507		Py_DECREF(getnewargs);
2508		if (args != NULL && !PyTuple_Check(args)) {
2509			PyErr_SetString(PyExc_TypeError,
2510				"__getnewargs__ should return a tuple");
2511			goto end;
2512		}
2513	}
2514	else {
2515		PyErr_Clear();
2516		args = PyTuple_New(0);
2517	}
2518	if (args == NULL)
2519		goto end;
2520
2521	getstate = PyObject_GetAttrString(obj, "__getstate__");
2522	if (getstate != NULL) {
2523		state = PyObject_CallObject(getstate, NULL);
2524		Py_DECREF(getstate);
2525	}
2526	else {
2527		state = PyObject_GetAttrString(obj, "__dict__");
2528		if (state == NULL) {
2529			PyErr_Clear();
2530			state = Py_None;
2531			Py_INCREF(state);
2532		}
2533		names = slotnames(cls);
2534		if (names == NULL)
2535			goto end;
2536		if (names != Py_None) {
2537			assert(PyList_Check(names));
2538			slots = PyDict_New();
2539			if (slots == NULL)
2540				goto end;
2541			n = 0;
2542			/* Can't pre-compute the list size; the list
2543			   is stored on the class so accessible to other
2544			   threads, which may be run by DECREF */
2545			for (i = 0; i < PyList_GET_SIZE(names); i++) {
2546				PyObject *name, *value;
2547				name = PyList_GET_ITEM(names, i);
2548				value = PyObject_GetAttr(obj, name);
2549				if (value == NULL)
2550					PyErr_Clear();
2551				else {
2552					int err = PyDict_SetItem(slots, name,
2553								 value);
2554					Py_DECREF(value);
2555					if (err)
2556						goto end;
2557					n++;
2558				}
2559			}
2560			if (n) {
2561				state = Py_BuildValue("(NO)", state, slots);
2562				if (state == NULL)
2563					goto end;
2564			}
2565		}
2566	}
2567
2568	if (!PyList_Check(obj)) {
2569		listitems = Py_None;
2570		Py_INCREF(listitems);
2571	}
2572	else {
2573		listitems = PyObject_GetIter(obj);
2574		if (listitems == NULL)
2575			goto end;
2576	}
2577
2578	if (!PyDict_Check(obj)) {
2579		dictitems = Py_None;
2580		Py_INCREF(dictitems);
2581	}
2582	else {
2583		dictitems = PyObject_CallMethod(obj, "iteritems", "");
2584		if (dictitems == NULL)
2585			goto end;
2586	}
2587
2588	copy_reg = import_copy_reg();
2589	if (copy_reg == NULL)
2590		goto end;
2591	newobj = PyObject_GetAttrString(copy_reg, "__newobj__");
2592	if (newobj == NULL)
2593		goto end;
2594
2595	n = PyTuple_GET_SIZE(args);
2596	args2 = PyTuple_New(n+1);
2597	if (args2 == NULL)
2598		goto end;
2599	PyTuple_SET_ITEM(args2, 0, cls);
2600	cls = NULL;
2601	for (i = 0; i < n; i++) {
2602		PyObject *v = PyTuple_GET_ITEM(args, i);
2603		Py_INCREF(v);
2604		PyTuple_SET_ITEM(args2, i+1, v);
2605	}
2606
2607	res = Py_BuildValue("(OOOOO)",
2608			    newobj, args2, state, listitems, dictitems);
2609
2610  end:
2611	Py_XDECREF(cls);
2612	Py_XDECREF(args);
2613	Py_XDECREF(args2);
2614	Py_XDECREF(state);
2615	Py_XDECREF(names);
2616	Py_XDECREF(listitems);
2617	Py_XDECREF(dictitems);
2618	Py_XDECREF(copy_reg);
2619	Py_XDECREF(newobj);
2620	return res;
2621}
2622
2623static PyObject *
2624object_reduce_ex(PyObject *self, PyObject *args)
2625{
2626	/* Call copy_reg._reduce_ex(self, proto) */
2627	PyObject *reduce, *copy_reg, *res;
2628	int proto = 0;
2629
2630	if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
2631		return NULL;
2632
2633	reduce = PyObject_GetAttrString(self, "__reduce__");
2634	if (reduce == NULL)
2635		PyErr_Clear();
2636	else {
2637		PyObject *cls, *clsreduce, *objreduce;
2638		int override;
2639		cls = PyObject_GetAttrString(self, "__class__");
2640		if (cls == NULL) {
2641			Py_DECREF(reduce);
2642			return NULL;
2643		}
2644		clsreduce = PyObject_GetAttrString(cls, "__reduce__");
2645		Py_DECREF(cls);
2646		if (clsreduce == NULL) {
2647			Py_DECREF(reduce);
2648			return NULL;
2649		}
2650		objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
2651						 "__reduce__");
2652		override = (clsreduce != objreduce);
2653		Py_DECREF(clsreduce);
2654		if (override) {
2655			res = PyObject_CallObject(reduce, NULL);
2656			Py_DECREF(reduce);
2657			return res;
2658		}
2659		else
2660			Py_DECREF(reduce);
2661	}
2662
2663	if (proto >= 2)
2664		return reduce_2(self);
2665
2666	copy_reg = import_copy_reg();
2667	if (!copy_reg)
2668		return NULL;
2669
2670	res = PyEval_CallMethod(copy_reg, "_reduce_ex", "(Oi)", self, proto);
2671	Py_DECREF(copy_reg);
2672
2673	return res;
2674}
2675
2676static PyMethodDef object_methods[] = {
2677	{"__reduce_ex__", object_reduce_ex, METH_VARARGS,
2678	 PyDoc_STR("helper for pickle")},
2679	{"__reduce__", object_reduce_ex, METH_VARARGS,
2680	 PyDoc_STR("helper for pickle")},
2681	{0}
2682};
2683
2684
2685PyTypeObject PyBaseObject_Type = {
2686	PyObject_HEAD_INIT(&PyType_Type)
2687 	0,					/* ob_size */
2688	"object",				/* tp_name */
2689	sizeof(PyObject),			/* tp_basicsize */
2690	0,					/* tp_itemsize */
2691	(destructor)object_dealloc,		/* tp_dealloc */
2692	0,					/* tp_print */
2693	0,			 		/* tp_getattr */
2694	0,					/* tp_setattr */
2695	0,					/* tp_compare */
2696	object_repr,				/* tp_repr */
2697	0,					/* tp_as_number */
2698	0,					/* tp_as_sequence */
2699	0,					/* tp_as_mapping */
2700	object_hash,				/* tp_hash */
2701	0,					/* tp_call */
2702	object_str,				/* tp_str */
2703	PyObject_GenericGetAttr,		/* tp_getattro */
2704	PyObject_GenericSetAttr,		/* tp_setattro */
2705	0,					/* tp_as_buffer */
2706	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2707	PyDoc_STR("The most base type"),	/* tp_doc */
2708	0,					/* tp_traverse */
2709	0,					/* tp_clear */
2710	0,					/* tp_richcompare */
2711	0,					/* tp_weaklistoffset */
2712	0,					/* tp_iter */
2713	0,					/* tp_iternext */
2714	object_methods,				/* tp_methods */
2715	0,					/* tp_members */
2716	object_getsets,				/* tp_getset */
2717	0,					/* tp_base */
2718	0,					/* tp_dict */
2719	0,					/* tp_descr_get */
2720	0,					/* tp_descr_set */
2721	0,					/* tp_dictoffset */
2722	object_init,				/* tp_init */
2723	PyType_GenericAlloc,			/* tp_alloc */
2724	object_new,				/* tp_new */
2725	PyObject_Del,           		/* tp_free */
2726};
2727
2728
2729/* Initialize the __dict__ in a type object */
2730
2731static int
2732add_methods(PyTypeObject *type, PyMethodDef *meth)
2733{
2734	PyObject *dict = type->tp_dict;
2735
2736	for (; meth->ml_name != NULL; meth++) {
2737		PyObject *descr;
2738		if (PyDict_GetItemString(dict, meth->ml_name))
2739			continue;
2740		if (meth->ml_flags & METH_CLASS) {
2741			if (meth->ml_flags & METH_STATIC) {
2742				PyErr_SetString(PyExc_ValueError,
2743				     "method cannot be both class and static");
2744				return -1;
2745			}
2746			descr = PyDescr_NewClassMethod(type, meth);
2747		}
2748		else if (meth->ml_flags & METH_STATIC) {
2749			PyObject *cfunc = PyCFunction_New(meth, NULL);
2750			if (cfunc == NULL)
2751				return -1;
2752			descr = PyStaticMethod_New(cfunc);
2753			Py_DECREF(cfunc);
2754		}
2755		else {
2756			descr = PyDescr_NewMethod(type, meth);
2757		}
2758		if (descr == NULL)
2759			return -1;
2760		if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
2761			return -1;
2762		Py_DECREF(descr);
2763	}
2764	return 0;
2765}
2766
2767static int
2768add_members(PyTypeObject *type, PyMemberDef *memb)
2769{
2770	PyObject *dict = type->tp_dict;
2771
2772	for (; memb->name != NULL; memb++) {
2773		PyObject *descr;
2774		if (PyDict_GetItemString(dict, memb->name))
2775			continue;
2776		descr = PyDescr_NewMember(type, memb);
2777		if (descr == NULL)
2778			return -1;
2779		if (PyDict_SetItemString(dict, memb->name, descr) < 0)
2780			return -1;
2781		Py_DECREF(descr);
2782	}
2783	return 0;
2784}
2785
2786static int
2787add_getset(PyTypeObject *type, PyGetSetDef *gsp)
2788{
2789	PyObject *dict = type->tp_dict;
2790
2791	for (; gsp->name != NULL; gsp++) {
2792		PyObject *descr;
2793		if (PyDict_GetItemString(dict, gsp->name))
2794			continue;
2795		descr = PyDescr_NewGetSet(type, gsp);
2796
2797		if (descr == NULL)
2798			return -1;
2799		if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
2800			return -1;
2801		Py_DECREF(descr);
2802	}
2803	return 0;
2804}
2805
2806static void
2807inherit_special(PyTypeObject *type, PyTypeObject *base)
2808{
2809	int oldsize, newsize;
2810
2811	/* Special flag magic */
2812	if (!type->tp_as_buffer && base->tp_as_buffer) {
2813		type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
2814		type->tp_flags |=
2815			base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
2816	}
2817	if (!type->tp_as_sequence && base->tp_as_sequence) {
2818		type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
2819		type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
2820	}
2821	if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
2822	    (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
2823		if ((!type->tp_as_number && base->tp_as_number) ||
2824		    (!type->tp_as_sequence && base->tp_as_sequence)) {
2825			type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
2826			if (!type->tp_as_number && !type->tp_as_sequence) {
2827				type->tp_flags |= base->tp_flags &
2828					Py_TPFLAGS_HAVE_INPLACEOPS;
2829			}
2830		}
2831		/* Wow */
2832	}
2833	if (!type->tp_as_number && base->tp_as_number) {
2834		type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
2835		type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
2836	}
2837
2838	/* Copying basicsize is connected to the GC flags */
2839	oldsize = base->tp_basicsize;
2840	newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
2841	if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2842	    (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2843	    (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
2844	    (!type->tp_traverse && !type->tp_clear)) {
2845		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2846		if (type->tp_traverse == NULL)
2847			type->tp_traverse = base->tp_traverse;
2848		if (type->tp_clear == NULL)
2849			type->tp_clear = base->tp_clear;
2850	}
2851	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2852		/* The condition below could use some explanation.
2853		   It appears that tp_new is not inherited for static types
2854		   whose base class is 'object'; this seems to be a precaution
2855		   so that old extension types don't suddenly become
2856		   callable (object.__new__ wouldn't insure the invariants
2857		   that the extension type's own factory function ensures).
2858		   Heap types, of course, are under our control, so they do
2859		   inherit tp_new; static extension types that specify some
2860		   other built-in type as the default are considered
2861		   new-style-aware so they also inherit object.__new__. */
2862		if (base != &PyBaseObject_Type ||
2863		    (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
2864			if (type->tp_new == NULL)
2865				type->tp_new = base->tp_new;
2866		}
2867	}
2868	type->tp_basicsize = newsize;
2869
2870	/* Copy other non-function slots */
2871
2872#undef COPYVAL
2873#define COPYVAL(SLOT) \
2874	if (type->SLOT == 0) type->SLOT = base->SLOT
2875
2876	COPYVAL(tp_itemsize);
2877	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
2878		COPYVAL(tp_weaklistoffset);
2879	}
2880	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2881		COPYVAL(tp_dictoffset);
2882	}
2883}
2884
2885static void
2886inherit_slots(PyTypeObject *type, PyTypeObject *base)
2887{
2888	PyTypeObject *basebase;
2889
2890#undef SLOTDEFINED
2891#undef COPYSLOT
2892#undef COPYNUM
2893#undef COPYSEQ
2894#undef COPYMAP
2895#undef COPYBUF
2896
2897#define SLOTDEFINED(SLOT) \
2898	(base->SLOT != 0 && \
2899	 (basebase == NULL || base->SLOT != basebase->SLOT))
2900
2901#define COPYSLOT(SLOT) \
2902	if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
2903
2904#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
2905#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
2906#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
2907#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
2908
2909	/* This won't inherit indirect slots (from tp_as_number etc.)
2910	   if type doesn't provide the space. */
2911
2912	if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
2913		basebase = base->tp_base;
2914		if (basebase->tp_as_number == NULL)
2915			basebase = NULL;
2916		COPYNUM(nb_add);
2917		COPYNUM(nb_subtract);
2918		COPYNUM(nb_multiply);
2919		COPYNUM(nb_divide);
2920		COPYNUM(nb_remainder);
2921		COPYNUM(nb_divmod);
2922		COPYNUM(nb_power);
2923		COPYNUM(nb_negative);
2924		COPYNUM(nb_positive);
2925		COPYNUM(nb_absolute);
2926		COPYNUM(nb_nonzero);
2927		COPYNUM(nb_invert);
2928		COPYNUM(nb_lshift);
2929		COPYNUM(nb_rshift);
2930		COPYNUM(nb_and);
2931		COPYNUM(nb_xor);
2932		COPYNUM(nb_or);
2933		COPYNUM(nb_coerce);
2934		COPYNUM(nb_int);
2935		COPYNUM(nb_long);
2936		COPYNUM(nb_float);
2937		COPYNUM(nb_oct);
2938		COPYNUM(nb_hex);
2939		COPYNUM(nb_inplace_add);
2940		COPYNUM(nb_inplace_subtract);
2941		COPYNUM(nb_inplace_multiply);
2942		COPYNUM(nb_inplace_divide);
2943		COPYNUM(nb_inplace_remainder);
2944		COPYNUM(nb_inplace_power);
2945		COPYNUM(nb_inplace_lshift);
2946		COPYNUM(nb_inplace_rshift);
2947		COPYNUM(nb_inplace_and);
2948		COPYNUM(nb_inplace_xor);
2949		COPYNUM(nb_inplace_or);
2950		if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
2951			COPYNUM(nb_true_divide);
2952			COPYNUM(nb_floor_divide);
2953			COPYNUM(nb_inplace_true_divide);
2954			COPYNUM(nb_inplace_floor_divide);
2955		}
2956	}
2957
2958	if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
2959		basebase = base->tp_base;
2960		if (basebase->tp_as_sequence == NULL)
2961			basebase = NULL;
2962		COPYSEQ(sq_length);
2963		COPYSEQ(sq_concat);
2964		COPYSEQ(sq_repeat);
2965		COPYSEQ(sq_item);
2966		COPYSEQ(sq_slice);
2967		COPYSEQ(sq_ass_item);
2968		COPYSEQ(sq_ass_slice);
2969		COPYSEQ(sq_contains);
2970		COPYSEQ(sq_inplace_concat);
2971		COPYSEQ(sq_inplace_repeat);
2972	}
2973
2974	if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
2975		basebase = base->tp_base;
2976		if (basebase->tp_as_mapping == NULL)
2977			basebase = NULL;
2978		COPYMAP(mp_length);
2979		COPYMAP(mp_subscript);
2980		COPYMAP(mp_ass_subscript);
2981	}
2982
2983	if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
2984		basebase = base->tp_base;
2985		if (basebase->tp_as_buffer == NULL)
2986			basebase = NULL;
2987		COPYBUF(bf_getreadbuffer);
2988		COPYBUF(bf_getwritebuffer);
2989		COPYBUF(bf_getsegcount);
2990		COPYBUF(bf_getcharbuffer);
2991	}
2992
2993	basebase = base->tp_base;
2994
2995	COPYSLOT(tp_dealloc);
2996	COPYSLOT(tp_print);
2997	if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
2998		type->tp_getattr = base->tp_getattr;
2999		type->tp_getattro = base->tp_getattro;
3000	}
3001	if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
3002		type->tp_setattr = base->tp_setattr;
3003		type->tp_setattro = base->tp_setattro;
3004	}
3005	/* tp_compare see tp_richcompare */
3006	COPYSLOT(tp_repr);
3007	/* tp_hash see tp_richcompare */
3008	COPYSLOT(tp_call);
3009	COPYSLOT(tp_str);
3010	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
3011		if (type->tp_compare == NULL &&
3012		    type->tp_richcompare == NULL &&
3013		    type->tp_hash == NULL)
3014		{
3015			type->tp_compare = base->tp_compare;
3016			type->tp_richcompare = base->tp_richcompare;
3017			type->tp_hash = base->tp_hash;
3018		}
3019	}
3020	else {
3021		COPYSLOT(tp_compare);
3022	}
3023	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
3024		COPYSLOT(tp_iter);
3025		COPYSLOT(tp_iternext);
3026	}
3027	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
3028		COPYSLOT(tp_descr_get);
3029		COPYSLOT(tp_descr_set);
3030		COPYSLOT(tp_dictoffset);
3031		COPYSLOT(tp_init);
3032		COPYSLOT(tp_alloc);
3033		COPYSLOT(tp_free);
3034		COPYSLOT(tp_is_gc);
3035	}
3036}
3037
3038static int add_operators(PyTypeObject *);
3039
3040int
3041PyType_Ready(PyTypeObject *type)
3042{
3043	PyObject *dict, *bases;
3044	PyTypeObject *base;
3045	int i, n;
3046
3047	if (type->tp_flags & Py_TPFLAGS_READY) {
3048		assert(type->tp_dict != NULL);
3049		return 0;
3050	}
3051	assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
3052
3053	type->tp_flags |= Py_TPFLAGS_READYING;
3054
3055	/* Initialize tp_base (defaults to BaseObject unless that's us) */
3056	base = type->tp_base;
3057	if (base == NULL && type != &PyBaseObject_Type)
3058		base = type->tp_base = &PyBaseObject_Type;
3059
3060	/* Initialize the base class */
3061	if (base && base->tp_dict == NULL) {
3062		if (PyType_Ready(base) < 0)
3063			goto error;
3064	}
3065
3066	/* Initialize ob_type if NULL.  This means extensions that want to be
3067	   compilable separately on Windows can call PyType_Ready() instead of
3068	   initializing the ob_type field of their type objects. */
3069	if (type->ob_type == NULL)
3070		type->ob_type = base->ob_type;
3071
3072	/* Initialize tp_bases */
3073	bases = type->tp_bases;
3074	if (bases == NULL) {
3075		if (base == NULL)
3076			bases = PyTuple_New(0);
3077		else
3078			bases = Py_BuildValue("(O)", base);
3079		if (bases == NULL)
3080			goto error;
3081		type->tp_bases = bases;
3082	}
3083
3084	/* Initialize tp_dict */
3085	dict = type->tp_dict;
3086	if (dict == NULL) {
3087		dict = PyDict_New();
3088		if (dict == NULL)
3089			goto error;
3090		type->tp_dict = dict;
3091	}
3092
3093	/* Add type-specific descriptors to tp_dict */
3094	if (add_operators(type) < 0)
3095		goto error;
3096	if (type->tp_methods != NULL) {
3097		if (add_methods(type, type->tp_methods) < 0)
3098			goto error;
3099	}
3100	if (type->tp_members != NULL) {
3101		if (add_members(type, type->tp_members) < 0)
3102			goto error;
3103	}
3104	if (type->tp_getset != NULL) {
3105		if (add_getset(type, type->tp_getset) < 0)
3106			goto error;
3107	}
3108
3109	/* Calculate method resolution order */
3110	if (mro_internal(type) < 0) {
3111		goto error;
3112	}
3113
3114	/* Inherit special flags from dominant base */
3115	if (type->tp_base != NULL)
3116		inherit_special(type, type->tp_base);
3117
3118	/* Initialize tp_dict properly */
3119	bases = type->tp_mro;
3120	assert(bases != NULL);
3121	assert(PyTuple_Check(bases));
3122	n = PyTuple_GET_SIZE(bases);
3123	for (i = 1; i < n; i++) {
3124		PyObject *b = PyTuple_GET_ITEM(bases, i);
3125		if (PyType_Check(b))
3126			inherit_slots(type, (PyTypeObject *)b);
3127	}
3128
3129	/* if the type dictionary doesn't contain a __doc__, set it from
3130	   the tp_doc slot.
3131	 */
3132	if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
3133		if (type->tp_doc != NULL) {
3134			PyObject *doc = PyString_FromString(type->tp_doc);
3135			PyDict_SetItemString(type->tp_dict, "__doc__", doc);
3136			Py_DECREF(doc);
3137		} else {
3138			PyDict_SetItemString(type->tp_dict,
3139					     "__doc__", Py_None);
3140		}
3141	}
3142
3143	/* Some more special stuff */
3144	base = type->tp_base;
3145	if (base != NULL) {
3146		if (type->tp_as_number == NULL)
3147			type->tp_as_number = base->tp_as_number;
3148		if (type->tp_as_sequence == NULL)
3149			type->tp_as_sequence = base->tp_as_sequence;
3150		if (type->tp_as_mapping == NULL)
3151			type->tp_as_mapping = base->tp_as_mapping;
3152		if (type->tp_as_buffer == NULL)
3153			type->tp_as_buffer = base->tp_as_buffer;
3154	}
3155
3156	/* Link into each base class's list of subclasses */
3157	bases = type->tp_bases;
3158	n = PyTuple_GET_SIZE(bases);
3159	for (i = 0; i < n; i++) {
3160		PyObject *b = PyTuple_GET_ITEM(bases, i);
3161		if (PyType_Check(b) &&
3162		    add_subclass((PyTypeObject *)b, type) < 0)
3163			goto error;
3164	}
3165
3166	/* All done -- set the ready flag */
3167	assert(type->tp_dict != NULL);
3168	type->tp_flags =
3169		(type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
3170	return 0;
3171
3172  error:
3173	type->tp_flags &= ~Py_TPFLAGS_READYING;
3174	return -1;
3175}
3176
3177static int
3178add_subclass(PyTypeObject *base, PyTypeObject *type)
3179{
3180	int i;
3181	PyObject *list, *ref, *new;
3182
3183	list = base->tp_subclasses;
3184	if (list == NULL) {
3185		base->tp_subclasses = list = PyList_New(0);
3186		if (list == NULL)
3187			return -1;
3188	}
3189	assert(PyList_Check(list));
3190	new = PyWeakref_NewRef((PyObject *)type, NULL);
3191	i = PyList_GET_SIZE(list);
3192	while (--i >= 0) {
3193		ref = PyList_GET_ITEM(list, i);
3194		assert(PyWeakref_CheckRef(ref));
3195		if (PyWeakref_GET_OBJECT(ref) == Py_None)
3196			return PyList_SetItem(list, i, new);
3197	}
3198	i = PyList_Append(list, new);
3199	Py_DECREF(new);
3200	return i;
3201}
3202
3203static void
3204remove_subclass(PyTypeObject *base, PyTypeObject *type)
3205{
3206	int i;
3207	PyObject *list, *ref;
3208
3209	list = base->tp_subclasses;
3210	if (list == NULL) {
3211		return;
3212	}
3213	assert(PyList_Check(list));
3214	i = PyList_GET_SIZE(list);
3215	while (--i >= 0) {
3216		ref = PyList_GET_ITEM(list, i);
3217		assert(PyWeakref_CheckRef(ref));
3218		if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
3219			/* this can't fail, right? */
3220			PySequence_DelItem(list, i);
3221			return;
3222		}
3223	}
3224}
3225
3226/* Generic wrappers for overloadable 'operators' such as __getitem__ */
3227
3228/* There's a wrapper *function* for each distinct function typedef used
3229   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
3230   wrapper *table* for each distinct operation (e.g. __len__, __add__).
3231   Most tables have only one entry; the tables for binary operators have two
3232   entries, one regular and one with reversed arguments. */
3233
3234static PyObject *
3235wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
3236{
3237	inquiry func = (inquiry)wrapped;
3238	int res;
3239
3240	if (!PyArg_ParseTuple(args, ""))
3241		return NULL;
3242	res = (*func)(self);
3243	if (res == -1 && PyErr_Occurred())
3244		return NULL;
3245	return PyInt_FromLong((long)res);
3246}
3247
3248static PyObject *
3249wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
3250{
3251	binaryfunc func = (binaryfunc)wrapped;
3252	PyObject *other;
3253
3254	if (!PyArg_ParseTuple(args, "O", &other))
3255		return NULL;
3256	return (*func)(self, other);
3257}
3258
3259static PyObject *
3260wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
3261{
3262	binaryfunc func = (binaryfunc)wrapped;
3263	PyObject *other;
3264
3265	if (!PyArg_ParseTuple(args, "O", &other))
3266		return NULL;
3267	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
3268	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
3269		Py_INCREF(Py_NotImplemented);
3270		return Py_NotImplemented;
3271	}
3272	return (*func)(self, other);
3273}
3274
3275static PyObject *
3276wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3277{
3278	binaryfunc func = (binaryfunc)wrapped;
3279	PyObject *other;
3280
3281	if (!PyArg_ParseTuple(args, "O", &other))
3282		return NULL;
3283	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
3284	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
3285		Py_INCREF(Py_NotImplemented);
3286		return Py_NotImplemented;
3287	}
3288	return (*func)(other, self);
3289}
3290
3291static PyObject *
3292wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
3293{
3294	coercion func = (coercion)wrapped;
3295	PyObject *other, *res;
3296	int ok;
3297
3298	if (!PyArg_ParseTuple(args, "O", &other))
3299		return NULL;
3300	ok = func(&self, &other);
3301	if (ok < 0)
3302		return NULL;
3303	if (ok > 0) {
3304		Py_INCREF(Py_NotImplemented);
3305		return Py_NotImplemented;
3306	}
3307	res = PyTuple_New(2);
3308	if (res == NULL) {
3309		Py_DECREF(self);
3310		Py_DECREF(other);
3311		return NULL;
3312	}
3313	PyTuple_SET_ITEM(res, 0, self);
3314	PyTuple_SET_ITEM(res, 1, other);
3315	return res;
3316}
3317
3318static PyObject *
3319wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
3320{
3321	ternaryfunc func = (ternaryfunc)wrapped;
3322	PyObject *other;
3323	PyObject *third = Py_None;
3324
3325	/* Note: This wrapper only works for __pow__() */
3326
3327	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3328		return NULL;
3329	return (*func)(self, other, third);
3330}
3331
3332static PyObject *
3333wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
3334{
3335	ternaryfunc func = (ternaryfunc)wrapped;
3336	PyObject *other;
3337	PyObject *third = Py_None;
3338
3339	/* Note: This wrapper only works for __pow__() */
3340
3341	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
3342		return NULL;
3343	return (*func)(other, self, third);
3344}
3345
3346static PyObject *
3347wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
3348{
3349	unaryfunc func = (unaryfunc)wrapped;
3350
3351	if (!PyArg_ParseTuple(args, ""))
3352		return NULL;
3353	return (*func)(self);
3354}
3355
3356static PyObject *
3357wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
3358{
3359	intargfunc func = (intargfunc)wrapped;
3360	int i;
3361
3362	if (!PyArg_ParseTuple(args, "i", &i))
3363		return NULL;
3364	return (*func)(self, i);
3365}
3366
3367static int
3368getindex(PyObject *self, PyObject *arg)
3369{
3370	int i;
3371
3372	i = PyInt_AsLong(arg);
3373	if (i == -1 && PyErr_Occurred())
3374		return -1;
3375	if (i < 0) {
3376		PySequenceMethods *sq = self->ob_type->tp_as_sequence;
3377		if (sq && sq->sq_length) {
3378			int n = (*sq->sq_length)(self);
3379			if (n < 0)
3380				return -1;
3381			i += n;
3382		}
3383	}
3384	return i;
3385}
3386
3387static PyObject *
3388wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
3389{
3390	intargfunc func = (intargfunc)wrapped;
3391	PyObject *arg;
3392	int i;
3393
3394	if (PyTuple_GET_SIZE(args) == 1) {
3395		arg = PyTuple_GET_ITEM(args, 0);
3396		i = getindex(self, arg);
3397		if (i == -1 && PyErr_Occurred())
3398			return NULL;
3399		return (*func)(self, i);
3400	}
3401	PyArg_ParseTuple(args, "O", &arg);
3402	assert(PyErr_Occurred());
3403	return NULL;
3404}
3405
3406static PyObject *
3407wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
3408{
3409	intintargfunc func = (intintargfunc)wrapped;
3410	int i, j;
3411
3412	if (!PyArg_ParseTuple(args, "ii", &i, &j))
3413		return NULL;
3414	return (*func)(self, i, j);
3415}
3416
3417static PyObject *
3418wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
3419{
3420	intobjargproc func = (intobjargproc)wrapped;
3421	int i, res;
3422	PyObject *arg, *value;
3423
3424	if (!PyArg_ParseTuple(args, "OO", &arg, &value))
3425		return NULL;
3426	i = getindex(self, arg);
3427	if (i == -1 && PyErr_Occurred())
3428		return NULL;
3429	res = (*func)(self, i, value);
3430	if (res == -1 && PyErr_Occurred())
3431		return NULL;
3432	Py_INCREF(Py_None);
3433	return Py_None;
3434}
3435
3436static PyObject *
3437wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
3438{
3439	intobjargproc func = (intobjargproc)wrapped;
3440	int i, res;
3441	PyObject *arg;
3442
3443	if (!PyArg_ParseTuple(args, "O", &arg))
3444		return NULL;
3445	i = getindex(self, arg);
3446	if (i == -1 && PyErr_Occurred())
3447		return NULL;
3448	res = (*func)(self, i, NULL);
3449	if (res == -1 && PyErr_Occurred())
3450		return NULL;
3451	Py_INCREF(Py_None);
3452	return Py_None;
3453}
3454
3455static PyObject *
3456wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
3457{
3458	intintobjargproc func = (intintobjargproc)wrapped;
3459	int i, j, res;
3460	PyObject *value;
3461
3462	if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
3463		return NULL;
3464	res = (*func)(self, i, j, value);
3465	if (res == -1 && PyErr_Occurred())
3466		return NULL;
3467	Py_INCREF(Py_None);
3468	return Py_None;
3469}
3470
3471static PyObject *
3472wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
3473{
3474	intintobjargproc func = (intintobjargproc)wrapped;
3475	int i, j, res;
3476
3477	if (!PyArg_ParseTuple(args, "ii", &i, &j))
3478		return NULL;
3479	res = (*func)(self, i, j, NULL);
3480	if (res == -1 && PyErr_Occurred())
3481		return NULL;
3482	Py_INCREF(Py_None);
3483	return Py_None;
3484}
3485
3486/* XXX objobjproc is a misnomer; should be objargpred */
3487static PyObject *
3488wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
3489{
3490	objobjproc func = (objobjproc)wrapped;
3491	int res;
3492	PyObject *value;
3493
3494	if (!PyArg_ParseTuple(args, "O", &value))
3495		return NULL;
3496	res = (*func)(self, value);
3497	if (res == -1 && PyErr_Occurred())
3498		return NULL;
3499	return PyInt_FromLong((long)res);
3500}
3501
3502static PyObject *
3503wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
3504{
3505	objobjargproc func = (objobjargproc)wrapped;
3506	int res;
3507	PyObject *key, *value;
3508
3509	if (!PyArg_ParseTuple(args, "OO", &key, &value))
3510		return NULL;
3511	res = (*func)(self, key, value);
3512	if (res == -1 && PyErr_Occurred())
3513		return NULL;
3514	Py_INCREF(Py_None);
3515	return Py_None;
3516}
3517
3518static PyObject *
3519wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
3520{
3521	objobjargproc func = (objobjargproc)wrapped;
3522	int res;
3523	PyObject *key;
3524
3525	if (!PyArg_ParseTuple(args, "O", &key))
3526		return NULL;
3527	res = (*func)(self, key, NULL);
3528	if (res == -1 && PyErr_Occurred())
3529		return NULL;
3530	Py_INCREF(Py_None);
3531	return Py_None;
3532}
3533
3534static PyObject *
3535wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
3536{
3537	cmpfunc func = (cmpfunc)wrapped;
3538	int res;
3539	PyObject *other;
3540
3541	if (!PyArg_ParseTuple(args, "O", &other))
3542		return NULL;
3543	if (other->ob_type->tp_compare != func &&
3544	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
3545		PyErr_Format(
3546			PyExc_TypeError,
3547			"%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
3548			self->ob_type->tp_name,
3549			self->ob_type->tp_name,
3550			other->ob_type->tp_name);
3551		return NULL;
3552	}
3553	res = (*func)(self, other);
3554	if (PyErr_Occurred())
3555		return NULL;
3556	return PyInt_FromLong((long)res);
3557}
3558
3559static PyObject *
3560wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
3561{
3562	setattrofunc func = (setattrofunc)wrapped;
3563	int res;
3564	PyObject *name, *value;
3565
3566	if (!PyArg_ParseTuple(args, "OO", &name, &value))
3567		return NULL;
3568	res = (*func)(self, name, value);
3569	if (res < 0)
3570		return NULL;
3571	Py_INCREF(Py_None);
3572	return Py_None;
3573}
3574
3575static PyObject *
3576wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
3577{
3578	setattrofunc func = (setattrofunc)wrapped;
3579	int res;
3580	PyObject *name;
3581
3582	if (!PyArg_ParseTuple(args, "O", &name))
3583		return NULL;
3584	res = (*func)(self, name, NULL);
3585	if (res < 0)
3586		return NULL;
3587	Py_INCREF(Py_None);
3588	return Py_None;
3589}
3590
3591static PyObject *
3592wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
3593{
3594	hashfunc func = (hashfunc)wrapped;
3595	long res;
3596
3597	if (!PyArg_ParseTuple(args, ""))
3598		return NULL;
3599	res = (*func)(self);
3600	if (res == -1 && PyErr_Occurred())
3601		return NULL;
3602	return PyInt_FromLong(res);
3603}
3604
3605static PyObject *
3606wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
3607{
3608	ternaryfunc func = (ternaryfunc)wrapped;
3609
3610	return (*func)(self, args, kwds);
3611}
3612
3613static PyObject *
3614wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
3615{
3616	richcmpfunc func = (richcmpfunc)wrapped;
3617	PyObject *other;
3618
3619	if (!PyArg_ParseTuple(args, "O", &other))
3620		return NULL;
3621	return (*func)(self, other, op);
3622}
3623
3624#undef RICHCMP_WRAPPER
3625#define RICHCMP_WRAPPER(NAME, OP) \
3626static PyObject * \
3627richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
3628{ \
3629	return wrap_richcmpfunc(self, args, wrapped, OP); \
3630}
3631
3632RICHCMP_WRAPPER(lt, Py_LT)
3633RICHCMP_WRAPPER(le, Py_LE)
3634RICHCMP_WRAPPER(eq, Py_EQ)
3635RICHCMP_WRAPPER(ne, Py_NE)
3636RICHCMP_WRAPPER(gt, Py_GT)
3637RICHCMP_WRAPPER(ge, Py_GE)
3638
3639static PyObject *
3640wrap_next(PyObject *self, PyObject *args, void *wrapped)
3641{
3642	unaryfunc func = (unaryfunc)wrapped;
3643	PyObject *res;
3644
3645	if (!PyArg_ParseTuple(args, ""))
3646		return NULL;
3647	res = (*func)(self);
3648	if (res == NULL && !PyErr_Occurred())
3649		PyErr_SetNone(PyExc_StopIteration);
3650	return res;
3651}
3652
3653static PyObject *
3654wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
3655{
3656	descrgetfunc func = (descrgetfunc)wrapped;
3657	PyObject *obj;
3658	PyObject *type = NULL;
3659
3660	if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
3661		return NULL;
3662	if (obj == Py_None)
3663		obj = NULL;
3664	if (type == Py_None)
3665		type = NULL;
3666	if (type == NULL &&obj == NULL) {
3667		PyErr_SetString(PyExc_TypeError,
3668				"__get__(None, None) is invalid");
3669		return NULL;
3670	}
3671	return (*func)(self, obj, type);
3672}
3673
3674static PyObject *
3675wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
3676{
3677	descrsetfunc func = (descrsetfunc)wrapped;
3678	PyObject *obj, *value;
3679	int ret;
3680
3681	if (!PyArg_ParseTuple(args, "OO", &obj, &value))
3682		return NULL;
3683	ret = (*func)(self, obj, value);
3684	if (ret < 0)
3685		return NULL;
3686	Py_INCREF(Py_None);
3687	return Py_None;
3688}
3689
3690static PyObject *
3691wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
3692{
3693	descrsetfunc func = (descrsetfunc)wrapped;
3694	PyObject *obj;
3695	int ret;
3696
3697	if (!PyArg_ParseTuple(args, "O", &obj))
3698		return NULL;
3699	ret = (*func)(self, obj, NULL);
3700	if (ret < 0)
3701		return NULL;
3702	Py_INCREF(Py_None);
3703	return Py_None;
3704}
3705
3706static PyObject *
3707wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
3708{
3709	initproc func = (initproc)wrapped;
3710
3711	if (func(self, args, kwds) < 0)
3712		return NULL;
3713	Py_INCREF(Py_None);
3714	return Py_None;
3715}
3716
3717static PyObject *
3718tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
3719{
3720	PyTypeObject *type, *subtype, *staticbase;
3721	PyObject *arg0, *res;
3722
3723	if (self == NULL || !PyType_Check(self))
3724		Py_FatalError("__new__() called with non-type 'self'");
3725	type = (PyTypeObject *)self;
3726	if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
3727		PyErr_Format(PyExc_TypeError,
3728			     "%s.__new__(): not enough arguments",
3729			     type->tp_name);
3730		return NULL;
3731	}
3732	arg0 = PyTuple_GET_ITEM(args, 0);
3733	if (!PyType_Check(arg0)) {
3734		PyErr_Format(PyExc_TypeError,
3735			     "%s.__new__(X): X is not a type object (%s)",
3736			     type->tp_name,
3737			     arg0->ob_type->tp_name);
3738		return NULL;
3739	}
3740	subtype = (PyTypeObject *)arg0;
3741	if (!PyType_IsSubtype(subtype, type)) {
3742		PyErr_Format(PyExc_TypeError,
3743			     "%s.__new__(%s): %s is not a subtype of %s",
3744			     type->tp_name,
3745			     subtype->tp_name,
3746			     subtype->tp_name,
3747			     type->tp_name);
3748		return NULL;
3749	}
3750
3751	/* Check that the use doesn't do something silly and unsafe like
3752	   object.__new__(dict).  To do this, we check that the
3753	   most derived base that's not a heap type is this type. */
3754	staticbase = subtype;
3755	while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
3756		staticbase = staticbase->tp_base;
3757	if (staticbase->tp_new != type->tp_new) {
3758		PyErr_Format(PyExc_TypeError,
3759			     "%s.__new__(%s) is not safe, use %s.__new__()",
3760			     type->tp_name,
3761			     subtype->tp_name,
3762			     staticbase == NULL ? "?" : staticbase->tp_name);
3763		return NULL;
3764	}
3765
3766	args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
3767	if (args == NULL)
3768		return NULL;
3769	res = type->tp_new(subtype, args, kwds);
3770	Py_DECREF(args);
3771	return res;
3772}
3773
3774static struct PyMethodDef tp_new_methoddef[] = {
3775	{"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
3776	 PyDoc_STR("T.__new__(S, ...) -> "
3777	 	   "a new object with type S, a subtype of T")},
3778	{0}
3779};
3780
3781static int
3782add_tp_new_wrapper(PyTypeObject *type)
3783{
3784	PyObject *func;
3785
3786	if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
3787		return 0;
3788	func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
3789	if (func == NULL)
3790		return -1;
3791	return PyDict_SetItemString(type->tp_dict, "__new__", func);
3792}
3793
3794/* Slot wrappers that call the corresponding __foo__ slot.  See comments
3795   below at override_slots() for more explanation. */
3796
3797#define SLOT0(FUNCNAME, OPSTR) \
3798static PyObject * \
3799FUNCNAME(PyObject *self) \
3800{ \
3801	static PyObject *cache_str; \
3802	return call_method(self, OPSTR, &cache_str, "()"); \
3803}
3804
3805#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
3806static PyObject * \
3807FUNCNAME(PyObject *self, ARG1TYPE arg1) \
3808{ \
3809	static PyObject *cache_str; \
3810	return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
3811}
3812
3813/* Boolean helper for SLOT1BINFULL().
3814   right.__class__ is a nontrivial subclass of left.__class__. */
3815static int
3816method_is_overloaded(PyObject *left, PyObject *right, char *name)
3817{
3818	PyObject *a, *b;
3819	int ok;
3820
3821	b = PyObject_GetAttrString((PyObject *)(right->ob_type), name);
3822	if (b == NULL) {
3823		PyErr_Clear();
3824		/* If right doesn't have it, it's not overloaded */
3825		return 0;
3826	}
3827
3828	a = PyObject_GetAttrString((PyObject *)(left->ob_type), name);
3829	if (a == NULL) {
3830		PyErr_Clear();
3831		Py_DECREF(b);
3832		/* If right has it but left doesn't, it's overloaded */
3833		return 1;
3834	}
3835
3836	ok = PyObject_RichCompareBool(a, b, Py_NE);
3837	Py_DECREF(a);
3838	Py_DECREF(b);
3839	if (ok < 0) {
3840		PyErr_Clear();
3841		return 0;
3842	}
3843
3844	return ok;
3845}
3846
3847
3848#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
3849static PyObject * \
3850FUNCNAME(PyObject *self, PyObject *other) \
3851{ \
3852	static PyObject *cache_str, *rcache_str; \
3853	int do_other = self->ob_type != other->ob_type && \
3854	    other->ob_type->tp_as_number != NULL && \
3855	    other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
3856	if (self->ob_type->tp_as_number != NULL && \
3857	    self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
3858		PyObject *r; \
3859		if (do_other && \
3860		    PyType_IsSubtype(other->ob_type, self->ob_type) && \
3861		    method_is_overloaded(self, other, ROPSTR)) { \
3862			r = call_maybe( \
3863				other, ROPSTR, &rcache_str, "(O)", self); \
3864			if (r != Py_NotImplemented) \
3865				return r; \
3866			Py_DECREF(r); \
3867			do_other = 0; \
3868		} \
3869		r = call_maybe( \
3870			self, OPSTR, &cache_str, "(O)", other); \
3871		if (r != Py_NotImplemented || \
3872		    other->ob_type == self->ob_type) \
3873			return r; \
3874		Py_DECREF(r); \
3875	} \
3876	if (do_other) { \
3877		return call_maybe( \
3878			other, ROPSTR, &rcache_str, "(O)", self); \
3879	} \
3880	Py_INCREF(Py_NotImplemented); \
3881	return Py_NotImplemented; \
3882}
3883
3884#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
3885	SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
3886
3887#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
3888static PyObject * \
3889FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
3890{ \
3891	static PyObject *cache_str; \
3892	return call_method(self, OPSTR, &cache_str, \
3893			   "(" ARGCODES ")", arg1, arg2); \
3894}
3895
3896static int
3897slot_sq_length(PyObject *self)
3898{
3899	static PyObject *len_str;
3900	PyObject *res = call_method(self, "__len__", &len_str, "()");
3901	int len;
3902
3903	if (res == NULL)
3904		return -1;
3905	len = (int)PyInt_AsLong(res);
3906	Py_DECREF(res);
3907	if (len == -1 && PyErr_Occurred())
3908		return -1;
3909	if (len < 0) {
3910		PyErr_SetString(PyExc_ValueError,
3911				"__len__() should return >= 0");
3912		return -1;
3913	}
3914	return len;
3915}
3916
3917SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
3918SLOT1(slot_sq_repeat, "__mul__", int, "i")
3919
3920/* Super-optimized version of slot_sq_item.
3921   Other slots could do the same... */
3922static PyObject *
3923slot_sq_item(PyObject *self, int i)
3924{
3925	static PyObject *getitem_str;
3926	PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
3927	descrgetfunc f;
3928
3929	if (getitem_str == NULL) {
3930		getitem_str = PyString_InternFromString("__getitem__");
3931		if (getitem_str == NULL)
3932			return NULL;
3933	}
3934	func = _PyType_Lookup(self->ob_type, getitem_str);
3935	if (func != NULL) {
3936		if ((f = func->ob_type->tp_descr_get) == NULL)
3937			Py_INCREF(func);
3938		else {
3939			func = f(func, self, (PyObject *)(self->ob_type));
3940			if (func == NULL) {
3941				return NULL;
3942			}
3943		}
3944		ival = PyInt_FromLong(i);
3945		if (ival != NULL) {
3946			args = PyTuple_New(1);
3947			if (args != NULL) {
3948				PyTuple_SET_ITEM(args, 0, ival);
3949				retval = PyObject_Call(func, args, NULL);
3950				Py_XDECREF(args);
3951				Py_XDECREF(func);
3952				return retval;
3953			}
3954		}
3955	}
3956	else {
3957		PyErr_SetObject(PyExc_AttributeError, getitem_str);
3958	}
3959	Py_XDECREF(args);
3960	Py_XDECREF(ival);
3961	Py_XDECREF(func);
3962	return NULL;
3963}
3964
3965SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
3966
3967static int
3968slot_sq_ass_item(PyObject *self, int index, PyObject *value)
3969{
3970	PyObject *res;
3971	static PyObject *delitem_str, *setitem_str;
3972
3973	if (value == NULL)
3974		res = call_method(self, "__delitem__", &delitem_str,
3975				  "(i)", index);
3976	else
3977		res = call_method(self, "__setitem__", &setitem_str,
3978				  "(iO)", index, value);
3979	if (res == NULL)
3980		return -1;
3981	Py_DECREF(res);
3982	return 0;
3983}
3984
3985static int
3986slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
3987{
3988	PyObject *res;
3989	static PyObject *delslice_str, *setslice_str;
3990
3991	if (value == NULL)
3992		res = call_method(self, "__delslice__", &delslice_str,
3993				  "(ii)", i, j);
3994	else
3995		res = call_method(self, "__setslice__", &setslice_str,
3996				  "(iiO)", i, j, value);
3997	if (res == NULL)
3998		return -1;
3999	Py_DECREF(res);
4000	return 0;
4001}
4002
4003static int
4004slot_sq_contains(PyObject *self, PyObject *value)
4005{
4006	PyObject *func, *res, *args;
4007	static PyObject *contains_str;
4008
4009	func = lookup_maybe(self, "__contains__", &contains_str);
4010
4011	if (func != NULL) {
4012		args = Py_BuildValue("(O)", value);
4013		if (args == NULL)
4014			res = NULL;
4015		else {
4016			res = PyObject_Call(func, args, NULL);
4017			Py_DECREF(args);
4018		}
4019		Py_DECREF(func);
4020		if (res == NULL)
4021			return -1;
4022		return PyObject_IsTrue(res);
4023	}
4024	else if (PyErr_Occurred())
4025		return -1;
4026	else {
4027		return _PySequence_IterSearch(self, value,
4028					      PY_ITERSEARCH_CONTAINS);
4029	}
4030}
4031
4032SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
4033SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
4034
4035#define slot_mp_length slot_sq_length
4036
4037SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
4038
4039static int
4040slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
4041{
4042	PyObject *res;
4043	static PyObject *delitem_str, *setitem_str;
4044
4045	if (value == NULL)
4046		res = call_method(self, "__delitem__", &delitem_str,
4047				  "(O)", key);
4048	else
4049		res = call_method(self, "__setitem__", &setitem_str,
4050				 "(OO)", key, value);
4051	if (res == NULL)
4052		return -1;
4053	Py_DECREF(res);
4054	return 0;
4055}
4056
4057SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
4058SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
4059SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
4060SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
4061SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
4062SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
4063
4064static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
4065
4066SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
4067	     nb_power, "__pow__", "__rpow__")
4068
4069static PyObject *
4070slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
4071{
4072	static PyObject *pow_str;
4073
4074	if (modulus == Py_None)
4075		return slot_nb_power_binary(self, other);
4076	/* Three-arg power doesn't use __rpow__.  But ternary_op
4077	   can call this when the second argument's type uses
4078	   slot_nb_power, so check before calling self.__pow__. */
4079	if (self->ob_type->tp_as_number != NULL &&
4080	    self->ob_type->tp_as_number->nb_power == slot_nb_power) {
4081		return call_method(self, "__pow__", &pow_str,
4082				   "(OO)", other, modulus);
4083	}
4084	Py_INCREF(Py_NotImplemented);
4085	return Py_NotImplemented;
4086}
4087
4088SLOT0(slot_nb_negative, "__neg__")
4089SLOT0(slot_nb_positive, "__pos__")
4090SLOT0(slot_nb_absolute, "__abs__")
4091
4092static int
4093slot_nb_nonzero(PyObject *self)
4094{
4095	PyObject *func, *args;
4096	static PyObject *nonzero_str, *len_str;
4097	int result = -1;
4098
4099	func = lookup_maybe(self, "__nonzero__", &nonzero_str);
4100	if (func == NULL) {
4101		if (PyErr_Occurred())
4102			return -1;
4103		func = lookup_maybe(self, "__len__", &len_str);
4104		if (func == NULL)
4105			return PyErr_Occurred() ? -1 : 1;
4106 	}
4107	args = PyTuple_New(0);
4108	if (args != NULL) {
4109		PyObject *temp = PyObject_Call(func, args, NULL);
4110		Py_DECREF(args);
4111		if (temp != NULL) {
4112			result = PyObject_IsTrue(temp);
4113			Py_DECREF(temp);
4114		}
4115	}
4116	Py_DECREF(func);
4117	return result;
4118}
4119
4120SLOT0(slot_nb_invert, "__invert__")
4121SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
4122SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
4123SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
4124SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
4125SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
4126
4127static int
4128slot_nb_coerce(PyObject **a, PyObject **b)
4129{
4130	static PyObject *coerce_str;
4131	PyObject *self = *a, *other = *b;
4132
4133	if (self->ob_type->tp_as_number != NULL &&
4134	    self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4135		PyObject *r;
4136		r = call_maybe(
4137			self, "__coerce__", &coerce_str, "(O)", other);
4138		if (r == NULL)
4139			return -1;
4140		if (r == Py_NotImplemented) {
4141			Py_DECREF(r);
4142		}
4143		else {
4144			if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4145				PyErr_SetString(PyExc_TypeError,
4146					"__coerce__ didn't return a 2-tuple");
4147				Py_DECREF(r);
4148				return -1;
4149			}
4150			*a = PyTuple_GET_ITEM(r, 0);
4151			Py_INCREF(*a);
4152			*b = PyTuple_GET_ITEM(r, 1);
4153			Py_INCREF(*b);
4154			Py_DECREF(r);
4155			return 0;
4156		}
4157	}
4158	if (other->ob_type->tp_as_number != NULL &&
4159	    other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
4160		PyObject *r;
4161		r = call_maybe(
4162			other, "__coerce__", &coerce_str, "(O)", self);
4163		if (r == NULL)
4164			return -1;
4165		if (r == Py_NotImplemented) {
4166			Py_DECREF(r);
4167			return 1;
4168		}
4169		if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
4170			PyErr_SetString(PyExc_TypeError,
4171					"__coerce__ didn't return a 2-tuple");
4172			Py_DECREF(r);
4173			return -1;
4174		}
4175		*a = PyTuple_GET_ITEM(r, 1);
4176		Py_INCREF(*a);
4177		*b = PyTuple_GET_ITEM(r, 0);
4178		Py_INCREF(*b);
4179		Py_DECREF(r);
4180		return 0;
4181	}
4182	return 1;
4183}
4184
4185SLOT0(slot_nb_int, "__int__")
4186SLOT0(slot_nb_long, "__long__")
4187SLOT0(slot_nb_float, "__float__")
4188SLOT0(slot_nb_oct, "__oct__")
4189SLOT0(slot_nb_hex, "__hex__")
4190SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
4191SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
4192SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
4193SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
4194SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
4195SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
4196SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
4197SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
4198SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
4199SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
4200SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
4201SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
4202	 "__floordiv__", "__rfloordiv__")
4203SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
4204SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
4205SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
4206
4207static int
4208half_compare(PyObject *self, PyObject *other)
4209{
4210	PyObject *func, *args, *res;
4211	static PyObject *cmp_str;
4212	int c;
4213
4214	func = lookup_method(self, "__cmp__", &cmp_str);
4215	if (func == NULL) {
4216		PyErr_Clear();
4217	}
4218	else {
4219		args = Py_BuildValue("(O)", other);
4220		if (args == NULL)
4221			res = NULL;
4222		else {
4223			res = PyObject_Call(func, args, NULL);
4224			Py_DECREF(args);
4225		}
4226		Py_DECREF(func);
4227		if (res != Py_NotImplemented) {
4228			if (res == NULL)
4229				return -2;
4230			c = PyInt_AsLong(res);
4231			Py_DECREF(res);
4232			if (c == -1 && PyErr_Occurred())
4233				return -2;
4234			return (c < 0) ? -1 : (c > 0) ? 1 : 0;
4235		}
4236		Py_DECREF(res);
4237	}
4238	return 2;
4239}
4240
4241/* This slot is published for the benefit of try_3way_compare in object.c */
4242int
4243_PyObject_SlotCompare(PyObject *self, PyObject *other)
4244{
4245	int c;
4246
4247	if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
4248		c = half_compare(self, other);
4249		if (c <= 1)
4250			return c;
4251	}
4252	if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
4253		c = half_compare(other, self);
4254		if (c < -1)
4255			return -2;
4256		if (c <= 1)
4257			return -c;
4258	}
4259	return (void *)self < (void *)other ? -1 :
4260		(void *)self > (void *)other ? 1 : 0;
4261}
4262
4263static PyObject *
4264slot_tp_repr(PyObject *self)
4265{
4266	PyObject *func, *res;
4267	static PyObject *repr_str;
4268
4269	func = lookup_method(self, "__repr__", &repr_str);
4270	if (func != NULL) {
4271		res = PyEval_CallObject(func, NULL);
4272		Py_DECREF(func);
4273		return res;
4274	}
4275	PyErr_Clear();
4276	return PyString_FromFormat("<%s object at %p>",
4277				   self->ob_type->tp_name, self);
4278}
4279
4280static PyObject *
4281slot_tp_str(PyObject *self)
4282{
4283	PyObject *func, *res;
4284	static PyObject *str_str;
4285
4286	func = lookup_method(self, "__str__", &str_str);
4287	if (func != NULL) {
4288		res = PyEval_CallObject(func, NULL);
4289		Py_DECREF(func);
4290		return res;
4291	}
4292	else {
4293		PyErr_Clear();
4294		return slot_tp_repr(self);
4295	}
4296}
4297
4298static long
4299slot_tp_hash(PyObject *self)
4300{
4301	PyObject *func;
4302	static PyObject *hash_str, *eq_str, *cmp_str;
4303	long h;
4304
4305	func = lookup_method(self, "__hash__", &hash_str);
4306
4307	if (func != NULL) {
4308		PyObject *res = PyEval_CallObject(func, NULL);
4309		Py_DECREF(func);
4310		if (res == NULL)
4311			return -1;
4312		h = PyInt_AsLong(res);
4313		Py_DECREF(res);
4314	}
4315	else {
4316		PyErr_Clear();
4317		func = lookup_method(self, "__eq__", &eq_str);
4318		if (func == NULL) {
4319			PyErr_Clear();
4320			func = lookup_method(self, "__cmp__", &cmp_str);
4321		}
4322		if (func != NULL) {
4323			Py_DECREF(func);
4324			PyErr_SetString(PyExc_TypeError, "unhashable type");
4325			return -1;
4326		}
4327		PyErr_Clear();
4328		h = _Py_HashPointer((void *)self);
4329	}
4330	if (h == -1 && !PyErr_Occurred())
4331		h = -2;
4332	return h;
4333}
4334
4335static PyObject *
4336slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
4337{
4338	static PyObject *call_str;
4339	PyObject *meth = lookup_method(self, "__call__", &call_str);
4340	PyObject *res;
4341
4342	if (meth == NULL)
4343		return NULL;
4344	res = PyObject_Call(meth, args, kwds);
4345	Py_DECREF(meth);
4346	return res;
4347}
4348
4349/* There are two slot dispatch functions for tp_getattro.
4350
4351   - slot_tp_getattro() is used when __getattribute__ is overridden
4352     but no __getattr__ hook is present;
4353
4354   - slot_tp_getattr_hook() is used when a __getattr__ hook is present.
4355
4356   The code in update_one_slot() always installs slot_tp_getattr_hook(); this
4357   detects the absence of __getattr__ and then installs the simpler slot if
4358   necessary. */
4359
4360static PyObject *
4361slot_tp_getattro(PyObject *self, PyObject *name)
4362{
4363	static PyObject *getattribute_str = NULL;
4364	return call_method(self, "__getattribute__", &getattribute_str,
4365			   "(O)", name);
4366}
4367
4368static PyObject *
4369slot_tp_getattr_hook(PyObject *self, PyObject *name)
4370{
4371	PyTypeObject *tp = self->ob_type;
4372	PyObject *getattr, *getattribute, *res;
4373	static PyObject *getattribute_str = NULL;
4374	static PyObject *getattr_str = NULL;
4375
4376	if (getattr_str == NULL) {
4377		getattr_str = PyString_InternFromString("__getattr__");
4378		if (getattr_str == NULL)
4379			return NULL;
4380	}
4381	if (getattribute_str == NULL) {
4382		getattribute_str =
4383			PyString_InternFromString("__getattribute__");
4384		if (getattribute_str == NULL)
4385			return NULL;
4386	}
4387	getattr = _PyType_Lookup(tp, getattr_str);
4388	if (getattr == NULL) {
4389		/* No __getattr__ hook: use a simpler dispatcher */
4390		tp->tp_getattro = slot_tp_getattro;
4391		return slot_tp_getattro(self, name);
4392	}
4393	getattribute = _PyType_Lookup(tp, getattribute_str);
4394	if (getattribute == NULL ||
4395	    (getattribute->ob_type == &PyWrapperDescr_Type &&
4396	     ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
4397	     (void *)PyObject_GenericGetAttr))
4398		res = PyObject_GenericGetAttr(self, name);
4399	else
4400		res = PyObject_CallFunction(getattribute, "OO", self, name);
4401	if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
4402		PyErr_Clear();
4403		res = PyObject_CallFunction(getattr, "OO", self, name);
4404	}
4405	return res;
4406}
4407
4408static int
4409slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
4410{
4411	PyObject *res;
4412	static PyObject *delattr_str, *setattr_str;
4413
4414	if (value == NULL)
4415		res = call_method(self, "__delattr__", &delattr_str,
4416				  "(O)", name);
4417	else
4418		res = call_method(self, "__setattr__", &setattr_str,
4419				  "(OO)", name, value);
4420	if (res == NULL)
4421		return -1;
4422	Py_DECREF(res);
4423	return 0;
4424}
4425
4426/* Map rich comparison operators to their __xx__ namesakes */
4427static char *name_op[] = {
4428	"__lt__",
4429	"__le__",
4430	"__eq__",
4431	"__ne__",
4432	"__gt__",
4433	"__ge__",
4434};
4435
4436static PyObject *
4437half_richcompare(PyObject *self, PyObject *other, int op)
4438{
4439	PyObject *func, *args, *res;
4440	static PyObject *op_str[6];
4441
4442	func = lookup_method(self, name_op[op], &op_str[op]);
4443	if (func == NULL) {
4444		PyErr_Clear();
4445		Py_INCREF(Py_NotImplemented);
4446		return Py_NotImplemented;
4447	}
4448	args = Py_BuildValue("(O)", other);
4449	if (args == NULL)
4450		res = NULL;
4451	else {
4452		res = PyObject_Call(func, args, NULL);
4453		Py_DECREF(args);
4454	}
4455	Py_DECREF(func);
4456	return res;
4457}
4458
4459/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
4460static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
4461
4462static PyObject *
4463slot_tp_richcompare(PyObject *self, PyObject *other, int op)
4464{
4465	PyObject *res;
4466
4467	if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
4468		res = half_richcompare(self, other, op);
4469		if (res != Py_NotImplemented)
4470			return res;
4471		Py_DECREF(res);
4472	}
4473	if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
4474		res = half_richcompare(other, self, swapped_op[op]);
4475		if (res != Py_NotImplemented) {
4476			return res;
4477		}
4478		Py_DECREF(res);
4479	}
4480	Py_INCREF(Py_NotImplemented);
4481	return Py_NotImplemented;
4482}
4483
4484static PyObject *
4485slot_tp_iter(PyObject *self)
4486{
4487	PyObject *func, *res;
4488	static PyObject *iter_str, *getitem_str;
4489
4490	func = lookup_method(self, "__iter__", &iter_str);
4491	if (func != NULL) {
4492		PyObject *args;
4493		args = res = PyTuple_New(0);
4494		if (args != NULL) {
4495			res = PyObject_Call(func, args, NULL);
4496			Py_DECREF(args);
4497		}
4498		Py_DECREF(func);
4499		return res;
4500	}
4501	PyErr_Clear();
4502	func = lookup_method(self, "__getitem__", &getitem_str);
4503	if (func == NULL) {
4504		PyErr_SetString(PyExc_TypeError,
4505				"iteration over non-sequence");
4506		return NULL;
4507	}
4508	Py_DECREF(func);
4509	return PySeqIter_New(self);
4510}
4511
4512static PyObject *
4513slot_tp_iternext(PyObject *self)
4514{
4515	static PyObject *next_str;
4516	return call_method(self, "next", &next_str, "()");
4517}
4518
4519static PyObject *
4520slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
4521{
4522	PyTypeObject *tp = self->ob_type;
4523	PyObject *get;
4524	static PyObject *get_str = NULL;
4525
4526	if (get_str == NULL) {
4527		get_str = PyString_InternFromString("__get__");
4528		if (get_str == NULL)
4529			return NULL;
4530	}
4531	get = _PyType_Lookup(tp, get_str);
4532	if (get == NULL) {
4533		/* Avoid further slowdowns */
4534		if (tp->tp_descr_get == slot_tp_descr_get)
4535			tp->tp_descr_get = NULL;
4536		Py_INCREF(self);
4537		return self;
4538	}
4539	if (obj == NULL)
4540		obj = Py_None;
4541	if (type == NULL)
4542		type = Py_None;
4543	return PyObject_CallFunction(get, "OOO", self, obj, type);
4544}
4545
4546static int
4547slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
4548{
4549	PyObject *res;
4550	static PyObject *del_str, *set_str;
4551
4552	if (value == NULL)
4553		res = call_method(self, "__delete__", &del_str,
4554				  "(O)", target);
4555	else
4556		res = call_method(self, "__set__", &set_str,
4557				  "(OO)", target, value);
4558	if (res == NULL)
4559		return -1;
4560	Py_DECREF(res);
4561	return 0;
4562}
4563
4564static int
4565slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
4566{
4567	static PyObject *init_str;
4568	PyObject *meth = lookup_method(self, "__init__", &init_str);
4569	PyObject *res;
4570
4571	if (meth == NULL)
4572		return -1;
4573	res = PyObject_Call(meth, args, kwds);
4574	Py_DECREF(meth);
4575	if (res == NULL)
4576		return -1;
4577	Py_DECREF(res);
4578	return 0;
4579}
4580
4581static PyObject *
4582slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4583{
4584	static PyObject *new_str;
4585	PyObject *func;
4586	PyObject *newargs, *x;
4587	int i, n;
4588
4589	if (new_str == NULL) {
4590		new_str = PyString_InternFromString("__new__");
4591		if (new_str == NULL)
4592			return NULL;
4593	}
4594	func = PyObject_GetAttr((PyObject *)type, new_str);
4595	if (func == NULL)
4596		return NULL;
4597	assert(PyTuple_Check(args));
4598	n = PyTuple_GET_SIZE(args);
4599	newargs = PyTuple_New(n+1);
4600	if (newargs == NULL)
4601		return NULL;
4602	Py_INCREF(type);
4603	PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
4604	for (i = 0; i < n; i++) {
4605		x = PyTuple_GET_ITEM(args, i);
4606		Py_INCREF(x);
4607		PyTuple_SET_ITEM(newargs, i+1, x);
4608	}
4609	x = PyObject_Call(func, newargs, kwds);
4610	Py_DECREF(newargs);
4611	Py_DECREF(func);
4612	return x;
4613}
4614
4615static void
4616slot_tp_del(PyObject *self)
4617{
4618	static PyObject *del_str = NULL;
4619	PyObject *del, *res;
4620	PyObject *error_type, *error_value, *error_traceback;
4621
4622	/* Temporarily resurrect the object. */
4623	assert(self->ob_refcnt == 0);
4624	self->ob_refcnt = 1;
4625
4626	/* Save the current exception, if any. */
4627	PyErr_Fetch(&error_type, &error_value, &error_traceback);
4628
4629	/* Execute __del__ method, if any. */
4630	del = lookup_maybe(self, "__del__", &del_str);
4631	if (del != NULL) {
4632		res = PyEval_CallObject(del, NULL);
4633		if (res == NULL)
4634			PyErr_WriteUnraisable(del);
4635		else
4636			Py_DECREF(res);
4637		Py_DECREF(del);
4638	}
4639
4640	/* Restore the saved exception. */
4641	PyErr_Restore(error_type, error_value, error_traceback);
4642
4643	/* Undo the temporary resurrection; can't use DECREF here, it would
4644	 * cause a recursive call.
4645	 */
4646	assert(self->ob_refcnt > 0);
4647	if (--self->ob_refcnt == 0)
4648		return;	/* this is the normal path out */
4649
4650	/* __del__ resurrected it!  Make it look like the original Py_DECREF
4651	 * never happened.
4652	 */
4653	{
4654		int refcnt = self->ob_refcnt;
4655		_Py_NewReference(self);
4656		self->ob_refcnt = refcnt;
4657	}
4658	assert(!PyType_IS_GC(self->ob_type) ||
4659	       _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
4660	/* If Py_REF_DEBUG, the original decref dropped _Py_RefTotal, but
4661	 * _Py_NewReference bumped it again, so that's a wash.
4662	 * If Py_TRACE_REFS, _Py_NewReference re-added self to the object
4663	 * chain, so no more to do there either.
4664	 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
4665	 * _Py_NewReference bumped tp_allocs:  both of those need to be
4666	 * undone.
4667	 */
4668#ifdef COUNT_ALLOCS
4669	--self->ob_type->tp_frees;
4670	--self->ob_type->tp_allocs;
4671#endif
4672}
4673
4674
4675/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
4676   functions.  The offsets here are relative to the 'PyHeapTypeObject'
4677   structure, which incorporates the additional structures used for numbers,
4678   sequences and mappings.
4679   Note that multiple names may map to the same slot (e.g. __eq__,
4680   __ne__ etc. all map to tp_richcompare) and one name may map to multiple
4681   slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
4682   terminated with an all-zero entry.  (This table is further initialized and
4683   sorted in init_slotdefs() below.) */
4684
4685typedef struct wrapperbase slotdef;
4686
4687#undef TPSLOT
4688#undef FLSLOT
4689#undef ETSLOT
4690#undef SQSLOT
4691#undef MPSLOT
4692#undef NBSLOT
4693#undef UNSLOT
4694#undef IBSLOT
4695#undef BINSLOT
4696#undef RBINSLOT
4697
4698#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4699	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4700	 PyDoc_STR(DOC)}
4701#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
4702	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4703	 PyDoc_STR(DOC), FLAGS}
4704#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4705	{NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
4706	 PyDoc_STR(DOC)}
4707#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4708	ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
4709#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4710	ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
4711#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4712	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
4713#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4714	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4715	       "x." NAME "() <==> " DOC)
4716#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
4717	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
4718	       "x." NAME "(y) <==> x" DOC "y")
4719#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
4720	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
4721	       "x." NAME "(y) <==> x" DOC "y")
4722#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
4723	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
4724	       "x." NAME "(y) <==> y" DOC "x")
4725
4726static slotdef slotdefs[] = {
4727	SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
4728	       "x.__len__() <==> len(x)"),
4729	SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
4730	       "x.__add__(y) <==> x+y"),
4731	SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4732	       "x.__mul__(n) <==> x*n"),
4733	SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
4734	       "x.__rmul__(n) <==> n*x"),
4735	SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
4736	       "x.__getitem__(y) <==> x[y]"),
4737	SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
4738	       "x.__getslice__(i, j) <==> x[i:j]"),
4739	SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
4740	       "x.__setitem__(i, y) <==> x[i]=y"),
4741	SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
4742	       "x.__delitem__(y) <==> del x[y]"),
4743	SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
4744	       wrap_intintobjargproc,
4745	       "x.__setslice__(i, j, y) <==> x[i:j]=y"),
4746	SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
4747	       "x.__delslice__(i, j) <==> del x[i:j]"),
4748	SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
4749	       "x.__contains__(y) <==> y in x"),
4750	SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
4751	       wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
4752	SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
4753	       wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
4754
4755	MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
4756	       "x.__len__() <==> len(x)"),
4757	MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
4758	       wrap_binaryfunc,
4759	       "x.__getitem__(y) <==> x[y]"),
4760	MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
4761	       wrap_objobjargproc,
4762	       "x.__setitem__(i, y) <==> x[i]=y"),
4763	MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
4764	       wrap_delitem,
4765	       "x.__delitem__(y) <==> del x[y]"),
4766
4767	BINSLOT("__add__", nb_add, slot_nb_add,
4768		"+"),
4769	RBINSLOT("__radd__", nb_add, slot_nb_add,
4770		 "+"),
4771	BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
4772		"-"),
4773	RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
4774		 "-"),
4775	BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
4776		"*"),
4777	RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
4778		 "*"),
4779	BINSLOT("__div__", nb_divide, slot_nb_divide,
4780		"/"),
4781	RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
4782		 "/"),
4783	BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
4784		"%"),
4785	RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
4786		 "%"),
4787	BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
4788		"divmod(x, y)"),
4789	RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
4790		 "divmod(y, x)"),
4791	NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
4792	       "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
4793	NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
4794	       "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
4795	UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
4796	UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
4797	UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
4798	       "abs(x)"),
4799	UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
4800	       "x != 0"),
4801	UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
4802	BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
4803	RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
4804	BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
4805	RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
4806	BINSLOT("__and__", nb_and, slot_nb_and, "&"),
4807	RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
4808	BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
4809	RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
4810	BINSLOT("__or__", nb_or, slot_nb_or, "|"),
4811	RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
4812	NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
4813	       "x.__coerce__(y) <==> coerce(x, y)"),
4814	UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
4815	       "int(x)"),
4816	UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
4817	       "long(x)"),
4818	UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
4819	       "float(x)"),
4820	UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
4821	       "oct(x)"),
4822	UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
4823	       "hex(x)"),
4824	IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
4825	       wrap_binaryfunc, "+"),
4826	IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
4827	       wrap_binaryfunc, "-"),
4828	IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
4829	       wrap_binaryfunc, "*"),
4830	IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
4831	       wrap_binaryfunc, "/"),
4832	IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
4833	       wrap_binaryfunc, "%"),
4834	IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
4835	       wrap_binaryfunc, "**"),
4836	IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
4837	       wrap_binaryfunc, "<<"),
4838	IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
4839	       wrap_binaryfunc, ">>"),
4840	IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
4841	       wrap_binaryfunc, "&"),
4842	IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
4843	       wrap_binaryfunc, "^"),
4844	IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
4845	       wrap_binaryfunc, "|"),
4846	BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4847	RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
4848	BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
4849	RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
4850	IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
4851	       slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
4852	IBSLOT("__itruediv__", nb_inplace_true_divide,
4853	       slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
4854
4855	TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
4856	       "x.__str__() <==> str(x)"),
4857	TPSLOT("__str__", tp_print, NULL, NULL, ""),
4858	TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
4859	       "x.__repr__() <==> repr(x)"),
4860	TPSLOT("__repr__", tp_print, NULL, NULL, ""),
4861	TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
4862	       "x.__cmp__(y) <==> cmp(x,y)"),
4863	TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
4864	       "x.__hash__() <==> hash(x)"),
4865	FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
4866	       "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
4867	TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
4868	       wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
4869	TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
4870	TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
4871	TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
4872	TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
4873	       "x.__setattr__('name', value) <==> x.name = value"),
4874	TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
4875	TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
4876	       "x.__delattr__('name') <==> del x.name"),
4877	TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
4878	TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
4879	       "x.__lt__(y) <==> x<y"),
4880	TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
4881	       "x.__le__(y) <==> x<=y"),
4882	TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
4883	       "x.__eq__(y) <==> x==y"),
4884	TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
4885	       "x.__ne__(y) <==> x!=y"),
4886	TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
4887	       "x.__gt__(y) <==> x>y"),
4888	TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
4889	       "x.__ge__(y) <==> x>=y"),
4890	TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
4891	       "x.__iter__() <==> iter(x)"),
4892	TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
4893	       "x.next() -> the next value, or raise StopIteration"),
4894	TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
4895	       "descr.__get__(obj[, type]) -> value"),
4896	TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
4897	       "descr.__set__(obj, value)"),
4898	TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
4899	       wrap_descr_delete, "descr.__delete__(obj)"),
4900	FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
4901	       "x.__init__(...) initializes x; "
4902	       "see x.__class__.__doc__ for signature",
4903	       PyWrapperFlag_KEYWORDS),
4904	TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
4905	TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
4906	{NULL}
4907};
4908
4909/* Given a type pointer and an offset gotten from a slotdef entry, return a
4910   pointer to the actual slot.  This is not quite the same as simply adding
4911   the offset to the type pointer, since it takes care to indirect through the
4912   proper indirection pointer (as_buffer, etc.); it returns NULL if the
4913   indirection pointer is NULL. */
4914static void **
4915slotptr(PyTypeObject *type, int offset)
4916{
4917	char *ptr;
4918
4919	/* Note: this depends on the order of the members of PyHeapTypeObject! */
4920	assert(offset >= 0);
4921	assert(offset < offsetof(PyHeapTypeObject, as_buffer));
4922	if (offset >= offsetof(PyHeapTypeObject, as_sequence)) {
4923		ptr = (void *)type->tp_as_sequence;
4924		offset -= offsetof(PyHeapTypeObject, as_sequence);
4925	}
4926	else if (offset >= offsetof(PyHeapTypeObject, as_mapping)) {
4927		ptr = (void *)type->tp_as_mapping;
4928		offset -= offsetof(PyHeapTypeObject, as_mapping);
4929	}
4930	else if (offset >= offsetof(PyHeapTypeObject, as_number)) {
4931		ptr = (void *)type->tp_as_number;
4932		offset -= offsetof(PyHeapTypeObject, as_number);
4933	}
4934	else {
4935		ptr = (void *)type;
4936	}
4937	if (ptr != NULL)
4938		ptr += offset;
4939	return (void **)ptr;
4940}
4941
4942/* Length of array of slotdef pointers used to store slots with the
4943   same __name__.  There should be at most MAX_EQUIV-1 slotdef entries with
4944   the same __name__, for any __name__. Since that's a static property, it is
4945   appropriate to declare fixed-size arrays for this. */
4946#define MAX_EQUIV 10
4947
4948/* Return a slot pointer for a given name, but ONLY if the attribute has
4949   exactly one slot function.  The name must be an interned string. */
4950static void **
4951resolve_slotdups(PyTypeObject *type, PyObject *name)
4952{
4953	/* XXX Maybe this could be optimized more -- but is it worth it? */
4954
4955	/* pname and ptrs act as a little cache */
4956	static PyObject *pname;
4957	static slotdef *ptrs[MAX_EQUIV];
4958	slotdef *p, **pp;
4959	void **res, **ptr;
4960
4961	if (pname != name) {
4962		/* Collect all slotdefs that match name into ptrs. */
4963		pname = name;
4964		pp = ptrs;
4965		for (p = slotdefs; p->name_strobj; p++) {
4966			if (p->name_strobj == name)
4967				*pp++ = p;
4968		}
4969		*pp = NULL;
4970	}
4971
4972	/* Look in all matching slots of the type; if exactly one of these has
4973	   a filled-in slot, return its value.  Otherwise return NULL. */
4974	res = NULL;
4975	for (pp = ptrs; *pp; pp++) {
4976		ptr = slotptr(type, (*pp)->offset);
4977		if (ptr == NULL || *ptr == NULL)
4978			continue;
4979		if (res != NULL)
4980			return NULL;
4981		res = ptr;
4982	}
4983	return res;
4984}
4985
4986/* Common code for update_these_slots() and fixup_slot_dispatchers().  This
4987   does some incredibly complex thinking and then sticks something into the
4988   slot.  (It sees if the adjacent slotdefs for the same slot have conflicting
4989   interests, and then stores a generic wrapper or a specific function into
4990   the slot.)  Return a pointer to the next slotdef with a different offset,
4991   because that's convenient  for fixup_slot_dispatchers(). */
4992static slotdef *
4993update_one_slot(PyTypeObject *type, slotdef *p)
4994{
4995	PyObject *descr;
4996	PyWrapperDescrObject *d;
4997	void *generic = NULL, *specific = NULL;
4998	int use_generic = 0;
4999	int offset = p->offset;
5000	void **ptr = slotptr(type, offset);
5001
5002	if (ptr == NULL) {
5003		do {
5004			++p;
5005		} while (p->offset == offset);
5006		return p;
5007	}
5008	do {
5009		descr = _PyType_Lookup(type, p->name_strobj);
5010		if (descr == NULL)
5011			continue;
5012		if (descr->ob_type == &PyWrapperDescr_Type) {
5013			void **tptr = resolve_slotdups(type, p->name_strobj);
5014			if (tptr == NULL || tptr == ptr)
5015				generic = p->function;
5016			d = (PyWrapperDescrObject *)descr;
5017			if (d->d_base->wrapper == p->wrapper &&
5018			    PyType_IsSubtype(type, d->d_type))
5019			{
5020				if (specific == NULL ||
5021				    specific == d->d_wrapped)
5022					specific = d->d_wrapped;
5023				else
5024					use_generic = 1;
5025			}
5026		}
5027		else if (descr->ob_type == &PyCFunction_Type &&
5028			 PyCFunction_GET_FUNCTION(descr) ==
5029			 (PyCFunction)tp_new_wrapper &&
5030			 strcmp(p->name, "__new__") == 0)
5031		{
5032			/* The __new__ wrapper is not a wrapper descriptor,
5033			   so must be special-cased differently.
5034			   If we don't do this, creating an instance will
5035			   always use slot_tp_new which will look up
5036			   __new__ in the MRO which will call tp_new_wrapper
5037			   which will look through the base classes looking
5038			   for a static base and call its tp_new (usually
5039			   PyType_GenericNew), after performing various
5040			   sanity checks and constructing a new argument
5041			   list.  Cut all that nonsense short -- this speeds
5042			   up instance creation tremendously. */
5043			specific = type->tp_new;
5044			/* XXX I'm not 100% sure that there isn't a hole
5045			   in this reasoning that requires additional
5046			   sanity checks.  I'll buy the first person to
5047			   point out a bug in this reasoning a beer. */
5048		}
5049		else {
5050			use_generic = 1;
5051			generic = p->function;
5052		}
5053	} while ((++p)->offset == offset);
5054	if (specific && !use_generic)
5055		*ptr = specific;
5056	else
5057		*ptr = generic;
5058	return p;
5059}
5060
5061static int recurse_down_subclasses(PyTypeObject *type, slotdef **pp,
5062				   PyObject *name);
5063
5064/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
5065   and then do the same for all this type's subtypes. */
5066static int
5067update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
5068{
5069	slotdef **pp;
5070
5071	for (pp = pp0; *pp; pp++)
5072		update_one_slot(type, *pp);
5073	return recurse_down_subclasses(type, pp0, name);
5074}
5075
5076/* Update the slots whose slotdefs are gathered in the pp array in all (direct
5077   or indirect) subclasses of type. */
5078static int
5079recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
5080{
5081	PyTypeObject *subclass;
5082	PyObject *ref, *subclasses, *dict;
5083	int i, n;
5084
5085	subclasses = type->tp_subclasses;
5086	if (subclasses == NULL)
5087		return 0;
5088	assert(PyList_Check(subclasses));
5089	n = PyList_GET_SIZE(subclasses);
5090	for (i = 0; i < n; i++) {
5091		ref = PyList_GET_ITEM(subclasses, i);
5092		assert(PyWeakref_CheckRef(ref));
5093		subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
5094		assert(subclass != NULL);
5095		if ((PyObject *)subclass == Py_None)
5096			continue;
5097		assert(PyType_Check(subclass));
5098		/* Avoid recursing down into unaffected classes */
5099		dict = subclass->tp_dict;
5100		if (dict != NULL && PyDict_Check(dict) &&
5101		    PyDict_GetItem(dict, name) != NULL)
5102			continue;
5103		if (update_these_slots(subclass, pp, name) < 0)
5104			return -1;
5105	}
5106	return 0;
5107}
5108
5109/* Comparison function for qsort() to compare slotdefs by their offset, and
5110   for equal offset by their address (to force a stable sort). */
5111static int
5112slotdef_cmp(const void *aa, const void *bb)
5113{
5114	const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
5115	int c = a->offset - b->offset;
5116	if (c != 0)
5117		return c;
5118	else
5119		return a - b;
5120}
5121
5122/* Initialize the slotdefs table by adding interned string objects for the
5123   names and sorting the entries. */
5124static void
5125init_slotdefs(void)
5126{
5127	slotdef *p;
5128	static int initialized = 0;
5129
5130	if (initialized)
5131		return;
5132	for (p = slotdefs; p->name; p++) {
5133		p->name_strobj = PyString_InternFromString(p->name);
5134		if (!p->name_strobj)
5135			Py_FatalError("Out of memory interning slotdef names");
5136	}
5137	qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
5138	      slotdef_cmp);
5139	initialized = 1;
5140}
5141
5142/* Update the slots after assignment to a class (type) attribute. */
5143static int
5144update_slot(PyTypeObject *type, PyObject *name)
5145{
5146	slotdef *ptrs[MAX_EQUIV];
5147	slotdef *p;
5148	slotdef **pp;
5149	int offset;
5150
5151	init_slotdefs();
5152	pp = ptrs;
5153	for (p = slotdefs; p->name; p++) {
5154		/* XXX assume name is interned! */
5155		if (p->name_strobj == name)
5156			*pp++ = p;
5157	}
5158	*pp = NULL;
5159	for (pp = ptrs; *pp; pp++) {
5160		p = *pp;
5161		offset = p->offset;
5162		while (p > slotdefs && (p-1)->offset == offset)
5163			--p;
5164		*pp = p;
5165	}
5166	if (ptrs[0] == NULL)
5167		return 0; /* Not an attribute that affects any slots */
5168	return update_these_slots(type, ptrs, name);
5169}
5170
5171/* Store the proper functions in the slot dispatches at class (type)
5172   definition time, based upon which operations the class overrides in its
5173   dict. */
5174static void
5175fixup_slot_dispatchers(PyTypeObject *type)
5176{
5177	slotdef *p;
5178
5179	init_slotdefs();
5180	for (p = slotdefs; p->name; )
5181		p = update_one_slot(type, p);
5182}
5183
5184static void
5185update_all_slots(PyTypeObject* type)
5186{
5187	slotdef *p;
5188
5189	init_slotdefs();
5190	for (p = slotdefs; p->name; p++) {
5191		/* update_slot returns int but can't actually fail */
5192		update_slot(type, p->name_strobj);
5193	}
5194}
5195
5196/* This function is called by PyType_Ready() to populate the type's
5197   dictionary with method descriptors for function slots.  For each
5198   function slot (like tp_repr) that's defined in the type, one or more
5199   corresponding descriptors are added in the type's tp_dict dictionary
5200   under the appropriate name (like __repr__).  Some function slots
5201   cause more than one descriptor to be added (for example, the nb_add
5202   slot adds both __add__ and __radd__ descriptors) and some function
5203   slots compete for the same descriptor (for example both sq_item and
5204   mp_subscript generate a __getitem__ descriptor).
5205
5206   In the latter case, the first slotdef entry encoutered wins.  Since
5207   slotdef entries are sorted by the offset of the slot in the
5208   PyHeapTypeObject, this gives us some control over disambiguating
5209   between competing slots: the members of PyHeapTypeObject are listed from most
5210   general to least general, so the most general slot is preferred.  In
5211   particular, because as_mapping comes before as_sequence, for a type
5212   that defines both mp_subscript and sq_item, mp_subscript wins.
5213
5214   This only adds new descriptors and doesn't overwrite entries in
5215   tp_dict that were previously defined.  The descriptors contain a
5216   reference to the C function they must call, so that it's safe if they
5217   are copied into a subtype's __dict__ and the subtype has a different
5218   C function in its slot -- calling the method defined by the
5219   descriptor will call the C function that was used to create it,
5220   rather than the C function present in the slot when it is called.
5221   (This is important because a subtype may have a C function in the
5222   slot that calls the method from the dictionary, and we want to avoid
5223   infinite recursion here.) */
5224
5225static int
5226add_operators(PyTypeObject *type)
5227{
5228	PyObject *dict = type->tp_dict;
5229	slotdef *p;
5230	PyObject *descr;
5231	void **ptr;
5232
5233	init_slotdefs();
5234	for (p = slotdefs; p->name; p++) {
5235		if (p->wrapper == NULL)
5236			continue;
5237		ptr = slotptr(type, p->offset);
5238		if (!ptr || !*ptr)
5239			continue;
5240		if (PyDict_GetItem(dict, p->name_strobj))
5241			continue;
5242		descr = PyDescr_NewWrapper(type, p, *ptr);
5243		if (descr == NULL)
5244			return -1;
5245		if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
5246			return -1;
5247		Py_DECREF(descr);
5248	}
5249	if (type->tp_new != NULL) {
5250		if (add_tp_new_wrapper(type) < 0)
5251			return -1;
5252	}
5253	return 0;
5254}
5255
5256
5257/* Cooperative 'super' */
5258
5259typedef struct {
5260	PyObject_HEAD
5261	PyTypeObject *type;
5262	PyObject *obj;
5263	PyTypeObject *obj_type;
5264} superobject;
5265
5266static PyMemberDef super_members[] = {
5267	{"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
5268	 "the class invoking super()"},
5269	{"__self__",  T_OBJECT, offsetof(superobject, obj), READONLY,
5270	 "the instance invoking super(); may be None"},
5271	{"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
5272	 "the type of the the instance invoking super(); may be None"},
5273	{0}
5274};
5275
5276static void
5277super_dealloc(PyObject *self)
5278{
5279	superobject *su = (superobject *)self;
5280
5281	_PyObject_GC_UNTRACK(self);
5282	Py_XDECREF(su->obj);
5283	Py_XDECREF(su->type);
5284	Py_XDECREF(su->obj_type);
5285	self->ob_type->tp_free(self);
5286}
5287
5288static PyObject *
5289super_repr(PyObject *self)
5290{
5291	superobject *su = (superobject *)self;
5292
5293	if (su->obj_type)
5294		return PyString_FromFormat(
5295			"<super: <class '%s'>, <%s object>>",
5296			su->type ? su->type->tp_name : "NULL",
5297			su->obj_type->tp_name);
5298	else
5299		return PyString_FromFormat(
5300			"<super: <class '%s'>, NULL>",
5301			su->type ? su->type->tp_name : "NULL");
5302}
5303
5304static PyObject *
5305super_getattro(PyObject *self, PyObject *name)
5306{
5307	superobject *su = (superobject *)self;
5308
5309	if (su->obj_type != NULL) {
5310		PyObject *mro, *res, *tmp, *dict;
5311		PyTypeObject *starttype;
5312		descrgetfunc f;
5313		int i, n;
5314
5315		starttype = su->obj_type;
5316		mro = starttype->tp_mro;
5317
5318		if (mro == NULL)
5319			n = 0;
5320		else {
5321			assert(PyTuple_Check(mro));
5322			n = PyTuple_GET_SIZE(mro);
5323		}
5324		for (i = 0; i < n; i++) {
5325			if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
5326				break;
5327		}
5328#if 0
5329		if (i >= n && PyType_Check(su->obj)) {
5330			starttype = (PyTypeObject *)(su->obj);
5331			mro = starttype->tp_mro;
5332			if (mro == NULL)
5333				n = 0;
5334			else {
5335				assert(PyTuple_Check(mro));
5336				n = PyTuple_GET_SIZE(mro);
5337			}
5338			for (i = 0; i < n; i++) {
5339				if ((PyObject *)(su->type) ==
5340				    PyTuple_GET_ITEM(mro, i))
5341					break;
5342			}
5343		}
5344#endif
5345		i++;
5346		res = NULL;
5347		for (; i < n; i++) {
5348			tmp = PyTuple_GET_ITEM(mro, i);
5349			if (PyType_Check(tmp))
5350				dict = ((PyTypeObject *)tmp)->tp_dict;
5351			else if (PyClass_Check(tmp))
5352				dict = ((PyClassObject *)tmp)->cl_dict;
5353			else
5354				continue;
5355			res = PyDict_GetItem(dict, name);
5356			if (res != NULL  && !PyDescr_IsData(res)) {
5357				Py_INCREF(res);
5358				f = res->ob_type->tp_descr_get;
5359				if (f != NULL) {
5360					tmp = f(res, su->obj,
5361						(PyObject *)starttype);
5362					Py_DECREF(res);
5363					res = tmp;
5364				}
5365				return res;
5366			}
5367		}
5368	}
5369	return PyObject_GenericGetAttr(self, name);
5370}
5371
5372static PyTypeObject *
5373supercheck(PyTypeObject *type, PyObject *obj)
5374{
5375	/* Check that a super() call makes sense.  Return a type object.
5376
5377	   obj can be a new-style class, or an instance of one:
5378
5379	   - If it is a class, it must be a subclass of 'type'.  This case is
5380	     used for class methods; the return value is obj.
5381
5382	   - If it is an instance, it must be an instance of 'type'.  This is
5383	     the normal case; the return value is obj.__class__.
5384
5385	   But... when obj is an instance, we want to allow for the case where
5386	   obj->ob_type is not a subclass of type, but obj.__class__ is!
5387	   This will allow using super() with a proxy for obj.
5388	*/
5389
5390	/* Check for first bullet above (special case) */
5391	if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
5392		Py_INCREF(obj);
5393		return (PyTypeObject *)obj;
5394	}
5395
5396	/* Normal case */
5397	if (PyType_IsSubtype(obj->ob_type, type)) {
5398		Py_INCREF(obj->ob_type);
5399		return obj->ob_type;
5400	}
5401	else {
5402		/* Try the slow way */
5403		static PyObject *class_str = NULL;
5404		PyObject *class_attr;
5405
5406		if (class_str == NULL) {
5407			class_str = PyString_FromString("__class__");
5408			if (class_str == NULL)
5409				return NULL;
5410		}
5411
5412		class_attr = PyObject_GetAttr(obj, class_str);
5413
5414		if (class_attr != NULL &&
5415		    PyType_Check(class_attr) &&
5416		    (PyTypeObject *)class_attr != obj->ob_type)
5417		{
5418			int ok = PyType_IsSubtype(
5419				(PyTypeObject *)class_attr, type);
5420			if (ok)
5421				return (PyTypeObject *)class_attr;
5422		}
5423
5424		if (class_attr == NULL)
5425			PyErr_Clear();
5426		else
5427			Py_DECREF(class_attr);
5428	}
5429
5430  	PyErr_SetString(PyExc_TypeError,
5431			"super(type, obj): "
5432			"obj must be an instance or subtype of type");
5433	return NULL;
5434}
5435
5436static PyObject *
5437super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
5438{
5439	superobject *su = (superobject *)self;
5440	superobject *new;
5441
5442	if (obj == NULL || obj == Py_None || su->obj != NULL) {
5443		/* Not binding to an object, or already bound */
5444		Py_INCREF(self);
5445		return self;
5446	}
5447	if (su->ob_type != &PySuper_Type)
5448		/* If su is an instance of a subclass of super,
5449		   call its type */
5450		return PyObject_CallFunction((PyObject *)su->ob_type,
5451					     "OO", su->type, obj);
5452	else {
5453		/* Inline the common case */
5454		PyTypeObject *obj_type = supercheck(su->type, obj);
5455		if (obj_type == NULL)
5456			return NULL;
5457		new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
5458							 NULL, NULL);
5459		if (new == NULL)
5460			return NULL;
5461		Py_INCREF(su->type);
5462		Py_INCREF(obj);
5463		new->type = su->type;
5464		new->obj = obj;
5465		new->obj_type = obj_type;
5466		return (PyObject *)new;
5467	}
5468}
5469
5470static int
5471super_init(PyObject *self, PyObject *args, PyObject *kwds)
5472{
5473	superobject *su = (superobject *)self;
5474	PyTypeObject *type;
5475	PyObject *obj = NULL;
5476	PyTypeObject *obj_type = NULL;
5477
5478	if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
5479		return -1;
5480	if (obj == Py_None)
5481		obj = NULL;
5482	if (obj != NULL) {
5483		obj_type = supercheck(type, obj);
5484		if (obj_type == NULL)
5485			return -1;
5486		Py_INCREF(obj);
5487	}
5488	Py_INCREF(type);
5489	su->type = type;
5490	su->obj = obj;
5491	su->obj_type = obj_type;
5492	return 0;
5493}
5494
5495PyDoc_STRVAR(super_doc,
5496"super(type) -> unbound super object\n"
5497"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
5498"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
5499"Typical use to call a cooperative superclass method:\n"
5500"class C(B):\n"
5501"    def meth(self, arg):\n"
5502"        super(C, self).meth(arg)");
5503
5504static int
5505super_traverse(PyObject *self, visitproc visit, void *arg)
5506{
5507	superobject *su = (superobject *)self;
5508	int err;
5509
5510#define VISIT(SLOT) \
5511	if (SLOT) { \
5512		err = visit((PyObject *)(SLOT), arg); \
5513		if (err) \
5514			return err; \
5515	}
5516
5517	VISIT(su->obj);
5518	VISIT(su->type);
5519	VISIT(su->obj_type);
5520
5521#undef VISIT
5522
5523	return 0;
5524}
5525
5526PyTypeObject PySuper_Type = {
5527	PyObject_HEAD_INIT(&PyType_Type)
5528	0,					/* ob_size */
5529	"super",				/* tp_name */
5530	sizeof(superobject),			/* tp_basicsize */
5531	0,					/* tp_itemsize */
5532	/* methods */
5533	super_dealloc,		 		/* tp_dealloc */
5534	0,					/* tp_print */
5535	0,					/* tp_getattr */
5536	0,					/* tp_setattr */
5537	0,					/* tp_compare */
5538	super_repr,				/* tp_repr */
5539	0,					/* tp_as_number */
5540	0,					/* tp_as_sequence */
5541	0,		       			/* tp_as_mapping */
5542	0,					/* tp_hash */
5543	0,					/* tp_call */
5544	0,					/* tp_str */
5545	super_getattro,				/* tp_getattro */
5546	0,					/* tp_setattro */
5547	0,					/* tp_as_buffer */
5548	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5549		Py_TPFLAGS_BASETYPE,		/* tp_flags */
5550 	super_doc,				/* tp_doc */
5551 	super_traverse,				/* tp_traverse */
5552 	0,					/* tp_clear */
5553	0,					/* tp_richcompare */
5554	0,					/* tp_weaklistoffset */
5555	0,					/* tp_iter */
5556	0,					/* tp_iternext */
5557	0,					/* tp_methods */
5558	super_members,				/* tp_members */
5559	0,					/* tp_getset */
5560	0,					/* tp_base */
5561	0,					/* tp_dict */
5562	super_descr_get,			/* tp_descr_get */
5563	0,					/* tp_descr_set */
5564	0,					/* tp_dictoffset */
5565	super_init,				/* tp_init */
5566	PyType_GenericAlloc,			/* tp_alloc */
5567	PyType_GenericNew,			/* tp_new */
5568	PyObject_GC_Del,        		/* tp_free */
5569};
5570