typeobject.c 113 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1 2
/* Type object implementation */

3
#include "Python.h"
4
#include "structmember.h"
Guido van Rossum's avatar
Guido van Rossum committed
5

6 7 8 9 10
#include <ctype.h>

/* The *real* layout of a type object when allocated on the heap */
/* XXX Should we publish this in a header file? */
typedef struct {
11 12
	/* Note: there's a dependency on the order of these members
	   in slotptr() below. */
13 14 15
	PyTypeObject type;
	PyNumberMethods as_number;
	PyMappingMethods as_mapping;
16 17 18 19 20
	PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
					  so that the mapping wins when both
					  the mapping and the sequence define
					  a given operator (e.g. __getitem__).
					  see add_operators() below. */
21 22 23 24 25
	PyBufferProcs as_buffer;
	PyObject *name, *slots;
	PyMemberDef members[1];
} etype;

26
static PyMemberDef type_members[] = {
27 28 29
	{"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
	{"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
	{"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
30
	{"__weakrefoffset__", T_LONG,
31 32 33 34 35 36 37 38 39
	 offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
	{"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
	{"__dictoffset__", T_LONG,
	 offsetof(PyTypeObject, tp_dictoffset), READONLY},
	{"__bases__", T_OBJECT, offsetof(PyTypeObject, tp_bases), READONLY},
	{"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
	{0}
};

40 41 42 43 44 45 46 47 48 49 50 51 52
static PyObject *
type_name(PyTypeObject *type, void *context)
{
	char *s;

	s = strrchr(type->tp_name, '.');
	if (s == NULL)
		s = type->tp_name;
	else
		s++;
	return PyString_FromString(s);
}

53 54 55
static PyObject *
type_module(PyTypeObject *type, void *context)
{
56 57 58 59 60 61 62 63 64
	PyObject *mod;
	char *s;

	s = strrchr(type->tp_name, '.');
	if (s != NULL)
		return PyString_FromStringAndSize(type->tp_name,
						  (int)(s - type->tp_name));
	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
		return PyString_FromString("__builtin__");
65
	mod = PyDict_GetItemString(type->tp_dict, "__module__");
66 67 68 69 70 71
	if (mod != NULL && PyString_Check(mod)) {
		Py_INCREF(mod);
		return mod;
	}
	PyErr_SetString(PyExc_AttributeError, "__module__");
	return NULL;
72
}
Guido van Rossum's avatar
Guido van Rossum committed
73

74 75 76
static int
type_set_module(PyTypeObject *type, PyObject *value, void *context)
{
77
	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
78 79 80 81 82 83 84 85 86 87 88 89 90
	    strrchr(type->tp_name, '.')) {
		PyErr_Format(PyExc_TypeError,
			     "can't set %s.__module__", type->tp_name);
		return -1;
	}
	if (!value) {
		PyErr_Format(PyExc_TypeError,
			     "can't delete %s.__module__", type->tp_name);
		return -1;
	}
	return PyDict_SetItemString(type->tp_dict, "__module__", value);
}

91
static PyObject *
92
type_dict(PyTypeObject *type, void *context)
93
{
94
	if (type->tp_dict == NULL) {
95 96
		Py_INCREF(Py_None);
		return Py_None;
97
	}
98 99 100
	return PyDictProxy_New(type->tp_dict);
}

101 102 103 104
static PyObject *
type_get_doc(PyTypeObject *type, void *context)
{
	PyObject *result;
Guido van Rossum's avatar
Guido van Rossum committed
105
	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
106 107
		return PyString_FromString(type->tp_doc);
	result = PyDict_GetItemString(type->tp_dict, "__doc__");
Guido van Rossum's avatar
Guido van Rossum committed
108 109 110 111 112
	if (result == NULL) {
		result = Py_None;
		Py_INCREF(result);
	}
	else if (result->ob_type->tp_descr_get) {
113 114
		result = result->ob_type->tp_descr_get(result, NULL,
						       (PyObject *)type);
Guido van Rossum's avatar
Guido van Rossum committed
115 116 117 118
	}
	else {
		Py_INCREF(result);
	}
119 120 121
	return result;
}

122
static PyGetSetDef type_getsets[] = {
123
	{"__name__", (getter)type_name, NULL, NULL},
124
	{"__module__", (getter)type_module, (setter)type_set_module, NULL},
125
	{"__dict__",  (getter)type_dict,  NULL, NULL},
126
	{"__doc__", (getter)type_get_doc, NULL, NULL},
127 128 129
	{0}
};

130 131 132 133 134 135 136 137 138 139
static int
type_compare(PyObject *v, PyObject *w)
{
	/* This is called with type objects only. So we
	   can just compare the addresses. */
	Py_uintptr_t vv = (Py_uintptr_t)v;
	Py_uintptr_t ww = (Py_uintptr_t)w;
	return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
}

140
static PyObject *
141
type_repr(PyTypeObject *type)
Guido van Rossum's avatar
Guido van Rossum committed
142
{
143
	PyObject *mod, *name, *rtn;
144
	char *kind;
145 146 147 148 149 150 151 152 153 154 155

	mod = type_module(type, NULL);
	if (mod == NULL)
		PyErr_Clear();
	else if (!PyString_Check(mod)) {
		Py_DECREF(mod);
		mod = NULL;
	}
	name = type_name(type, NULL);
	if (name == NULL)
		return NULL;
156

157 158 159 160 161
	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
		kind = "class";
	else
		kind = "type";

162
	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
163 164
		rtn = PyString_FromFormat("<%s '%s.%s'>",
					  kind,
165 166 167
					  PyString_AS_STRING(mod),
					  PyString_AS_STRING(name));
	}
168
	else
169
		rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
170

171 172
	Py_XDECREF(mod);
	Py_DECREF(name);
173
	return rtn;
Guido van Rossum's avatar
Guido van Rossum committed
174 175
}

176 177 178 179 180 181 182 183 184 185 186 187
static PyObject *
type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *obj;

	if (type->tp_new == NULL) {
		PyErr_Format(PyExc_TypeError,
			     "cannot create '%.100s' instances",
			     type->tp_name);
		return NULL;
	}

188
	obj = type->tp_new(type, args, kwds);
189
	if (obj != NULL) {
190 191 192 193 194 195 196
		/* Ugly exception: when the call was type(something),
		   don't call tp_init on the result. */
		if (type == &PyType_Type &&
		    PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
		    (kwds == NULL ||
		     (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
			return obj;
197 198 199 200
		/* If the returned object is not an instance of type,
		   it won't be initialized. */
		if (!PyType_IsSubtype(obj->ob_type, type))
			return obj;
201 202 203 204 205 206 207 208 209 210 211 212 213 214
		type = obj->ob_type;
		if (type->tp_init != NULL &&
		    type->tp_init(obj, args, kwds) < 0) {
			Py_DECREF(obj);
			obj = NULL;
		}
	}
	return obj;
}

PyObject *
PyType_GenericAlloc(PyTypeObject *type, int nitems)
{
	PyObject *obj;
215
	const size_t size = _PyObject_VAR_SIZE(type, nitems);
216 217

	if (PyType_IS_GC(type))
218
		obj = _PyObject_GC_Malloc(size);
219
	else
220
		obj = PyObject_MALLOC(size);
221

222
	if (obj == NULL)
223
		return PyErr_NoMemory();
224

225
	memset(obj, '\0', size);
226

227 228
	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
		Py_INCREF(type);
229

230 231 232 233
	if (type->tp_itemsize == 0)
		PyObject_INIT(obj, type);
	else
		(void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
234

235
	if (PyType_IS_GC(type))
236
		_PyObject_GC_TRACK(obj);
237 238 239 240 241 242 243 244 245
	return obj;
}

PyObject *
PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	return type->tp_alloc(type, 0);
}

246 247
/* Helpers for subtyping */

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
static int
traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
{
	int i, n;
	PyMemberDef *mp;

	n = type->ob_size;
	mp = ((etype *)type)->members;
	for (i = 0; i < n; i++, mp++) {
		if (mp->type == T_OBJECT_EX) {
			char *addr = (char *)self + mp->offset;
			PyObject *obj = *(PyObject **)addr;
			if (obj != NULL) {
				int err = visit(obj, arg);
				if (err)
					return err;
			}
		}
	}
	return 0;
}

270 271 272 273
static int
subtype_traverse(PyObject *self, visitproc visit, void *arg)
{
	PyTypeObject *type, *base;
274
	traverseproc basetraverse;
275

276 277
	/* Find the nearest base with a different tp_traverse,
	   and traverse slots while we're at it */
278
	type = self->ob_type;
279 280 281 282 283 284 285
	base = type;
	while ((basetraverse = base->tp_traverse) == subtype_traverse) {
		if (base->ob_size) {
			int err = traverse_slots(base, self, visit, arg);
			if (err)
				return err;
		}
286 287 288 289 290 291 292
		base = base->tp_base;
		assert(base);
	}

	if (type->tp_dictoffset != base->tp_dictoffset) {
		PyObject **dictptr = _PyObject_GetDictPtr(self);
		if (dictptr && *dictptr) {
293
			int err = visit(*dictptr, arg);
294 295 296 297 298
			if (err)
				return err;
		}
	}

299 300 301 302 303 304 305 306 307
	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
		/* For a heaptype, the instances count as references
		   to the type.  Traverse the type so the collector
		   can find cycles involving this link. */
		int err = visit((PyObject *)type, arg);
		if (err)
			return err;
	}

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
	if (basetraverse)
		return basetraverse(self, visit, arg);
	return 0;
}

static void
clear_slots(PyTypeObject *type, PyObject *self)
{
	int i, n;
	PyMemberDef *mp;

	n = type->ob_size;
	mp = ((etype *)type)->members;
	for (i = 0; i < n; i++, mp++) {
		if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
			char *addr = (char *)self + mp->offset;
			PyObject *obj = *(PyObject **)addr;
			if (obj != NULL) {
				Py_DECREF(obj);
				*(PyObject **)addr = NULL;
			}
		}
	}
}

static int
subtype_clear(PyObject *self)
{
	PyTypeObject *type, *base;
	inquiry baseclear;

	/* Find the nearest base with a different tp_clear
	   and clear slots while we're at it */
	type = self->ob_type;
	base = type;
	while ((baseclear = base->tp_clear) == subtype_clear) {
		if (base->ob_size)
			clear_slots(base, self);
		base = base->tp_base;
		assert(base);
	}

350 351
	/* There's no need to clear the instance dict (if any);
	   the collector will call its tp_clear handler. */
352 353 354

	if (baseclear)
		return baseclear(self);
355 356
	return 0;
}
357

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
staticforward PyObject *lookup_maybe(PyObject *, char *, PyObject **);

static int
call_finalizer(PyObject *self)
{
	static PyObject *del_str = NULL;
	PyObject *del, *res;
	PyObject *error_type, *error_value, *error_traceback;

	/* Temporarily resurrect the object. */
#ifdef Py_TRACE_REFS
#ifndef Py_REF_DEBUG
#   error "Py_TRACE_REFS defined but Py_REF_DEBUG not."
#endif
	/* much too complicated if Py_TRACE_REFS defined */
	_Py_NewReference((PyObject *)self);
#ifdef COUNT_ALLOCS
	/* compensate for boost in _Py_NewReference; note that
	 * _Py_RefTotal was also boosted; we'll knock that down later.
	 */
	self->ob_type->tp_allocs--;
#endif
#else /* !Py_TRACE_REFS */
	/* Py_INCREF boosts _Py_RefTotal if Py_REF_DEBUG is defined */
	Py_INCREF(self);
#endif /* !Py_TRACE_REFS */

	/* Save the current exception, if any. */
	PyErr_Fetch(&error_type, &error_value, &error_traceback);

	/* Execute __del__ method, if any. */
	del = lookup_maybe(self, "__del__", &del_str);
	if (del != NULL) {
		res = PyEval_CallObject(del, NULL);
		if (res == NULL)
			PyErr_WriteUnraisable(del);
		else
			Py_DECREF(res);
		Py_DECREF(del);
	}

	/* Restore the saved exception. */
	PyErr_Restore(error_type, error_value, error_traceback);

	/* Undo the temporary resurrection; can't use DECREF here, it would
	 * cause a recursive call.
	 */
#ifdef Py_REF_DEBUG
	/* _Py_RefTotal was boosted either by _Py_NewReference or
	 * Py_INCREF above.
	 */
	_Py_RefTotal--;
#endif
	if (--self->ob_refcnt > 0) {
#ifdef COUNT_ALLOCS
		self->ob_type->tp_frees--;
#endif
		_PyObject_GC_TRACK(self);
		return -1; /* __del__ added a reference; don't delete now */
	}
#ifdef Py_TRACE_REFS
	_Py_ForgetReference((PyObject *)self);
#ifdef COUNT_ALLOCS
	/* compensate for increment in _Py_ForgetReference */
	self->ob_type->tp_frees--;
#endif
#endif

	return 0;
}

429 430 431
static void
subtype_dealloc(PyObject *self)
{
432
	PyTypeObject *type, *base;
433
	destructor basedealloc;
434 435 436

	/* This exists so we can DECREF self->ob_type */

437 438 439
	if (call_finalizer(self) < 0)
		return;

440 441
	/* Find the nearest base with a different tp_dealloc
	   and clear slots while we're at it */
442
	type = self->ob_type;
443 444 445 446
	base = type;
	while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
		if (base->ob_size)
			clear_slots(base, self);
447 448
		base = base->tp_base;
		assert(base);
449 450
	}

451
	/* If we added a dict, DECREF it */
452 453 454 455 456 457 458 459
	if (type->tp_dictoffset && !base->tp_dictoffset) {
		PyObject **dictptr = _PyObject_GetDictPtr(self);
		if (dictptr != NULL) {
			PyObject *dict = *dictptr;
			if (dict != NULL) {
				Py_DECREF(dict);
				*dictptr = NULL;
			}
460 461 462
		}
	}

463
	/* If we added weaklist, we clear it */
464
	if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
465 466
		PyObject_ClearWeakRefs(self);

467 468
	/* Finalize GC if the base doesn't do GC and we do */
	if (PyType_IS_GC(type) && !PyType_IS_GC(base))
469
		_PyObject_GC_UNTRACK(self);
470 471

	/* Call the base tp_dealloc() */
472 473
	assert(basedealloc);
	basedealloc(self);
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

	/* Can't reference self beyond this point */
	if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
		Py_DECREF(type);
	}
}

staticforward PyTypeObject *solid_base(PyTypeObject *type);

/* type test with subclassing support */

int
PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
{
	PyObject *mro;

490 491 492
	if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
		return b == a || b == &PyBaseObject_Type;

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
	mro = a->tp_mro;
	if (mro != NULL) {
		/* Deal with multiple inheritance without recursion
		   by walking the MRO tuple */
		int i, n;
		assert(PyTuple_Check(mro));
		n = PyTuple_GET_SIZE(mro);
		for (i = 0; i < n; i++) {
			if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
				return 1;
		}
		return 0;
	}
	else {
		/* a is not completely initilized yet; follow tp_base */
		do {
			if (a == b)
				return 1;
			a = a->tp_base;
		} while (a != NULL);
		return b == &PyBaseObject_Type;
	}
}

517
/* Internal routines to do a method lookup in the type
518 519 520 521
   without looking in the instance dictionary
   (so we can't use PyObject_GetAttr) but still binding
   it to the instance.  The arguments are the object,
   the method name as a C string, and the address of a
522 523 524 525 526 527 528 529 530
   static variable used to cache the interned Python string.

   Two variants:

   - lookup_maybe() returns NULL without raising an exception
     when the _PyType_Lookup() call fails;

   - lookup_method() always raises an exception upon errors.
*/
531 532

static PyObject *
533
lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
534 535 536 537 538 539 540 541 542
{
	PyObject *res;

	if (*attrobj == NULL) {
		*attrobj = PyString_InternFromString(attrstr);
		if (*attrobj == NULL)
			return NULL;
	}
	res = _PyType_Lookup(self->ob_type, *attrobj);
543
	if (res != NULL) {
544 545 546 547 548 549 550 551 552
		descrgetfunc f;
		if ((f = res->ob_type->tp_descr_get) == NULL)
			Py_INCREF(res);
		else
			res = f(res, self, (PyObject *)(self->ob_type));
	}
	return res;
}

553 554 555 556 557 558 559 560 561
static PyObject *
lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
{
	PyObject *res = lookup_maybe(self, attrstr, attrobj);
	if (res == NULL && !PyErr_Occurred())
		PyErr_SetObject(PyExc_AttributeError, *attrobj);
	return res;
}

562 563 564 565
/* A variation of PyObject_CallMethod that uses lookup_method()
   instead of PyObject_GetAttrString().  This uses the same convention
   as lookup_method to cache the interned name string object. */

566
static PyObject *
567 568 569 570 571 572
call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
{
	va_list va;
	PyObject *args, *func = 0, *retval;
	va_start(va, format);

573
	func = lookup_maybe(o, name, nameobj);
574 575 576
	if (func == NULL) {
		va_end(va);
		if (!PyErr_Occurred())
577
			PyErr_SetObject(PyExc_AttributeError, *nameobj);
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
		return NULL;
	}

	if (format && *format)
		args = Py_VaBuildValue(format, va);
	else
		args = PyTuple_New(0);

	va_end(va);

	if (args == NULL)
		return NULL;

	assert(PyTuple_Check(args));
	retval = PyObject_Call(func, args, NULL);

	Py_DECREF(args);
	Py_DECREF(func);

	return retval;
}

/* Clone of call_method() that returns NotImplemented when the lookup fails. */

602
static PyObject *
603 604 605 606 607 608
call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
{
	va_list va;
	PyObject *args, *func = 0, *retval;
	va_start(va, format);

609
	func = lookup_maybe(o, name, nameobj);
610 611
	if (func == NULL) {
		va_end(va);
612 613 614 615
		if (!PyErr_Occurred()) {
			Py_INCREF(Py_NotImplemented);
			return Py_NotImplemented;
		}
Guido van Rossum's avatar
Guido van Rossum committed
616
		return NULL;
617 618 619 620 621 622 623 624 625
	}

	if (format && *format)
		args = Py_VaBuildValue(format, va);
	else
		args = PyTuple_New(0);

	va_end(va);

Guido van Rossum's avatar
Guido van Rossum committed
626
	if (args == NULL)
627 628
		return NULL;

Guido van Rossum's avatar
Guido van Rossum committed
629 630
	assert(PyTuple_Check(args));
	retval = PyObject_Call(func, args, NULL);
631 632 633 634 635 636 637

	Py_DECREF(args);
	Py_DECREF(func);

	return retval;
}

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
/* Method resolution order algorithm from "Putting Metaclasses to Work"
   by Forman and Danforth (Addison-Wesley 1999). */

static int
conservative_merge(PyObject *left, PyObject *right)
{
	int left_size;
	int right_size;
	int i, j, r, ok;
	PyObject *temp, *rr;

	assert(PyList_Check(left));
	assert(PyList_Check(right));

  again:
	left_size = PyList_GET_SIZE(left);
	right_size = PyList_GET_SIZE(right);
	for (i = 0; i < left_size; i++) {
		for (j = 0; j < right_size; j++) {
			if (PyList_GET_ITEM(left, i) ==
			    PyList_GET_ITEM(right, j)) {
				/* found a merge point */
				temp = PyList_New(0);
				if (temp == NULL)
					return -1;
				for (r = 0; r < j; r++) {
					rr = PyList_GET_ITEM(right, r);
					ok = PySequence_Contains(left, rr);
					if (ok < 0) {
						Py_DECREF(temp);
						return -1;
					}
					if (!ok) {
						ok = PyList_Append(temp, rr);
						if (ok < 0) {
							Py_DECREF(temp);
							return -1;
						}
					}
				}
				ok = PyList_SetSlice(left, i, i, temp);
				Py_DECREF(temp);
				if (ok < 0)
					return -1;
				ok = PyList_SetSlice(right, 0, j+1, NULL);
				if (ok < 0)
					return -1;
				goto again;
			}
		}
	}
	return PyList_SetSlice(left, left_size, left_size, right);
}

static int
serious_order_disagreements(PyObject *left, PyObject *right)
{
	return 0; /* XXX later -- for now, we cheat: "don't do that" */
}

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
static int
fill_classic_mro(PyObject *mro, PyObject *cls)
{
	PyObject *bases, *base;
	int i, n;

	assert(PyList_Check(mro));
	assert(PyClass_Check(cls));
	i = PySequence_Contains(mro, cls);
	if (i < 0)
		return -1;
	if (!i) {
		if (PyList_Append(mro, cls) < 0)
			return -1;
	}
	bases = ((PyClassObject *)cls)->cl_bases;
	assert(bases && PyTuple_Check(bases));
	n = PyTuple_GET_SIZE(bases);
	for (i = 0; i < n; i++) {
		base = PyTuple_GET_ITEM(bases, i);
		if (fill_classic_mro(mro, base) < 0)
			return -1;
	}
	return 0;
}

static PyObject *
classic_mro(PyObject *cls)
{
	PyObject *mro;

	assert(PyClass_Check(cls));
	mro = PyList_New(0);
	if (mro != NULL) {
		if (fill_classic_mro(mro, cls) == 0)
			return mro;
		Py_DECREF(mro);
	}
	return NULL;
}

739 740 741 742 743 744
static PyObject *
mro_implementation(PyTypeObject *type)
{
	int i, n, ok;
	PyObject *bases, *result;

745 746 747 748 749
	if(type->tp_dict == NULL) {
		if(PyType_Ready(type) < 0)
			return NULL;
	}

750 751 752 753 754 755
	bases = type->tp_bases;
	n = PyTuple_GET_SIZE(bases);
	result = Py_BuildValue("[O]", (PyObject *)type);
	if (result == NULL)
		return NULL;
	for (i = 0; i < n; i++) {
756 757 758 759 760 761 762
		PyObject *base = PyTuple_GET_ITEM(bases, i);
		PyObject *parentMRO;
		if (PyType_Check(base))
			parentMRO = PySequence_List(
				((PyTypeObject*)base)->tp_mro);
		else
			parentMRO = classic_mro(base);
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
		if (parentMRO == NULL) {
			Py_DECREF(result);
			return NULL;
		}
		if (serious_order_disagreements(result, parentMRO)) {
			Py_DECREF(result);
			return NULL;
		}
		ok = conservative_merge(result, parentMRO);
		Py_DECREF(parentMRO);
		if (ok < 0) {
			Py_DECREF(result);
			return NULL;
		}
	}
	return result;
}

static PyObject *
782
mro_external(PyObject *self)
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
{
	PyTypeObject *type = (PyTypeObject *)self;

	return mro_implementation(type);
}

static int
mro_internal(PyTypeObject *type)
{
	PyObject *mro, *result, *tuple;

	if (type->ob_type == &PyType_Type) {
		result = mro_implementation(type);
	}
	else {
798 799
		static PyObject *mro_str;
		mro = lookup_method((PyObject *)type, "mro", &mro_str);
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
		if (mro == NULL)
			return -1;
		result = PyObject_CallObject(mro, NULL);
		Py_DECREF(mro);
	}
	if (result == NULL)
		return -1;
	tuple = PySequence_Tuple(result);
	Py_DECREF(result);
	type->tp_mro = tuple;
	return 0;
}


/* Calculate the best base amongst multiple base classes.
   This is the first one that's on the path to the "solid base". */

static PyTypeObject *
best_base(PyObject *bases)
{
	int i, n;
	PyTypeObject *base, *winner, *candidate, *base_i;
822
	PyObject *base_proto;
823 824 825 826

	assert(PyTuple_Check(bases));
	n = PyTuple_GET_SIZE(bases);
	assert(n > 0);
827 828
	base = NULL;
	winner = NULL;
829
	for (i = 0; i < n; i++) {
830 831 832 833
		base_proto = PyTuple_GET_ITEM(bases, i);
		if (PyClass_Check(base_proto))
			continue;
		if (!PyType_Check(base_proto)) {
834 835 836 837 838
			PyErr_SetString(
				PyExc_TypeError,
				"bases must be types");
			return NULL;
		}
839
		base_i = (PyTypeObject *)base_proto;
840
		if (base_i->tp_dict == NULL) {
841
			if (PyType_Ready(base_i) < 0)
842 843 844
				return NULL;
		}
		candidate = solid_base(base_i);
845 846 847 848 849
		if (winner == NULL) {
			winner = candidate;
			base = base_i;
		}
		else if (PyType_IsSubtype(winner, candidate))
850 851 852 853 854 855 856 857 858 859 860 861 862
			;
		else if (PyType_IsSubtype(candidate, winner)) {
			winner = candidate;
			base = base_i;
		}
		else {
			PyErr_SetString(
				PyExc_TypeError,
				"multiple bases have "
				"instance lay-out conflict");
			return NULL;
		}
	}
Guido van Rossum's avatar
Guido van Rossum committed
863 864 865
	if (base == NULL)
		PyErr_SetString(PyExc_TypeError,
			"a new-style class can't have only classic bases");
866 867 868 869 870 871
	return base;
}

static int
extra_ivars(PyTypeObject *type, PyTypeObject *base)
{
872 873
	size_t t_size = type->tp_basicsize;
	size_t b_size = base->tp_basicsize;
874

875
	assert(t_size >= b_size); /* Else type smaller than base! */
876 877 878 879 880
	if (type->tp_itemsize || base->tp_itemsize) {
		/* If itemsize is involved, stricter rules */
		return t_size != b_size ||
			type->tp_itemsize != base->tp_itemsize;
	}
881 882 883 884 885 886 887 888
	if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
	    type->tp_weaklistoffset + sizeof(PyObject *) == t_size)
		t_size -= sizeof(PyObject *);
	if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
	    type->tp_dictoffset + sizeof(PyObject *) == t_size)
		t_size -= sizeof(PyObject *);

	return t_size != b_size;
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
}

static PyTypeObject *
solid_base(PyTypeObject *type)
{
	PyTypeObject *base;

	if (type->tp_base)
		base = solid_base(type->tp_base);
	else
		base = &PyBaseObject_Type;
	if (extra_ivars(type, base))
		return type;
	else
		return base;
}

staticforward void object_dealloc(PyObject *);
staticforward int object_init(PyObject *, PyObject *, PyObject *);
908
staticforward int update_slot(PyTypeObject *, PyObject *);
909
staticforward void fixup_slot_dispatchers(PyTypeObject *);
910

911 912 913 914 915 916 917 918 919 920 921 922
static PyObject *
subtype_dict(PyObject *obj, void *context)
{
	PyObject **dictptr = _PyObject_GetDictPtr(obj);
	PyObject *dict;

	if (dictptr == NULL) {
		PyErr_SetString(PyExc_AttributeError,
				"This object has no __dict__");
		return NULL;
	}
	dict = *dictptr;
923 924 925 926
	if (dict == NULL)
		*dictptr = dict = PyDict_New();
	Py_XINCREF(dict);
	return dict;
927 928
}

929 930 931 932 933 934 935 936 937 938 939
static int
subtype_setdict(PyObject *obj, PyObject *value, void *context)
{
	PyObject **dictptr = _PyObject_GetDictPtr(obj);
	PyObject *dict;

	if (dictptr == NULL) {
		PyErr_SetString(PyExc_AttributeError,
				"This object has no __dict__");
		return -1;
	}
940
	if (value != NULL && !PyDict_Check(value)) {
941 942 943 944 945
		PyErr_SetString(PyExc_TypeError,
				"__dict__ must be set to a dictionary");
		return -1;
	}
	dict = *dictptr;
946
	Py_XINCREF(value);
947 948 949 950 951
	*dictptr = value;
	Py_XDECREF(dict);
	return 0;
}

952
static PyGetSetDef subtype_getsets[] = {
953
	{"__dict__", subtype_dict, subtype_setdict, NULL},
954 955 956
	{0},
};

957 958 959 960 961 962 963 964 965 966 967
/* bozo: __getstate__ that raises TypeError */

static PyObject *
bozo_func(PyObject *self, PyObject *args)
{
	PyErr_SetString(PyExc_TypeError,
			"a class that defines __slots__ without "
			"defining __getstate__ cannot be pickled");
	return NULL;
}

968
static PyMethodDef bozo_ml = {"__getstate__", bozo_func, METH_VARARGS};
969 970 971

static PyObject *bozo_obj = NULL;

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
static int
valid_identifier(PyObject *s)
{
	char *p;
	int i, n;

	if (!PyString_Check(s)) {
		PyErr_SetString(PyExc_TypeError,
				"__slots__ must be strings");
		return 0;
	}
	p = PyString_AS_STRING(s);
	n = PyString_GET_SIZE(s);
	/* We must reject an empty name.  As a hack, we bump the
	   length to 1 so that the loop will balk on the trailing \0. */
	if (n == 0)
		n = 1;
	for (i = 0; i < n; i++, p++) {
		if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
			PyErr_SetString(PyExc_TypeError,
					"__slots__ must be identifiers");
			return 0;
		}
	}
	return 1;
}

999 1000 1001 1002 1003
static PyObject *
type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
{
	PyObject *name, *bases, *dict;
	static char *kwlist[] = {"name", "bases", "dict", 0};
1004 1005
	static char buffer[256];
	PyObject *slots, *tmp, *newslots;
1006
	PyTypeObject *type, *base, *tmptype, *winner;
1007
	etype *et;
1008
	PyMemberDef *mp;
1009
	int i, nbases, nslots, slotoffset, add_dict, add_weak;
1010

1011 1012 1013
	assert(args != NULL && PyTuple_Check(args));
	assert(kwds == NULL || PyDict_Check(kwds));

1014
	/* Special case: type(x) should return x->ob_type */
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
	{
		const int nargs = PyTuple_GET_SIZE(args);
		const int nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);

		if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
			PyObject *x = PyTuple_GET_ITEM(args, 0);
			Py_INCREF(x->ob_type);
			return (PyObject *) x->ob_type;
		}

		/* SF bug 475327 -- if that didn't trigger, we need 3
		   arguments. but PyArg_ParseTupleAndKeywords below may give
		   a msg saying type() needs exactly 3. */
		if (nargs + nkwds != 3) {
			PyErr_SetString(PyExc_TypeError,
					"type() takes 1 or 3 arguments");
			return NULL;
		}
1033 1034
	}

1035
	/* Check arguments: (name, bases, dict) */
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
					 &name,
					 &PyTuple_Type, &bases,
					 &PyDict_Type, &dict))
		return NULL;

	/* Determine the proper metatype to deal with this,
	   and check for metatype conflicts while we're at it.
	   Note that if some other metatype wins to contract,
	   it's possible that its instances are not types. */
	nbases = PyTuple_GET_SIZE(bases);
1047
	winner = metatype;
1048 1049 1050
	for (i = 0; i < nbases; i++) {
		tmp = PyTuple_GET_ITEM(bases, i);
		tmptype = tmp->ob_type;
1051 1052
		if (tmptype == &PyClass_Type)
			continue; /* Special case classic classes */
1053
		if (PyType_IsSubtype(winner, tmptype))
1054
			continue;
1055 1056
		if (PyType_IsSubtype(tmptype, winner)) {
			winner = tmptype;
1057 1058 1059 1060 1061 1062
			continue;
		}
		PyErr_SetString(PyExc_TypeError,
				"metatype conflict among bases");
		return NULL;
	}
1063 1064 1065 1066 1067
	if (winner != metatype) {
		if (winner->tp_new != type_new) /* Pass it to the winner */
			return winner->tp_new(winner, args, kwds);
		metatype = winner;
	}
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

	/* Adjust for empty tuple bases */
	if (nbases == 0) {
		bases = Py_BuildValue("(O)", &PyBaseObject_Type);
		if (bases == NULL)
			return NULL;
		nbases = 1;
	}
	else
		Py_INCREF(bases);

	/* XXX From here until type is allocated, "return NULL" leaks bases! */

	/* Calculate best base, and check that all bases are type objects */
	base = best_base(bases);
	if (base == NULL)
		return NULL;
	if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
		PyErr_Format(PyExc_TypeError,
			     "type '%.100s' is not an acceptable base type",
			     base->tp_name);
		return NULL;
	}

	/* Check for a __slots__ sequence variable in dict, and count it */
	slots = PyDict_GetItemString(dict, "__slots__");
	nslots = 0;
1095 1096
	add_dict = 0;
	add_weak = 0;
1097 1098 1099 1100 1101 1102 1103 1104 1105
	if (slots != NULL) {
		/* Make it into a tuple */
		if (PyString_Check(slots))
			slots = Py_BuildValue("(O)", slots);
		else
			slots = PySequence_Tuple(slots);
		if (slots == NULL)
			return NULL;
		nslots = PyTuple_GET_SIZE(slots);
1106 1107 1108 1109 1110 1111 1112
		if (nslots > 0 && base->tp_itemsize != 0) {
			PyErr_Format(PyExc_TypeError,
				     "nonempty __slots__ "
				     "not supported for subtype of '%s'",
				     base->tp_name);
			return NULL;
		}
1113
		for (i = 0; i < nslots; i++) {
1114
			if (!valid_identifier(PyTuple_GET_ITEM(slots, i))) {
1115 1116 1117 1118
				Py_DECREF(slots);
				return NULL;
			}
		}
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137

		newslots = PyTuple_New(nslots);
		if (newslots == NULL)
			return NULL;
		for (i = 0; i < nslots; i++) {
			tmp = PyTuple_GET_ITEM(slots, i);
			if (_Py_Mangle(PyString_AS_STRING(name),
				PyString_AS_STRING(tmp),
				buffer, sizeof(buffer)))
			{
				tmp = PyString_FromString(buffer);
			} else {
				Py_INCREF(tmp);
			}
			PyTuple_SET_ITEM(newslots, i, tmp);
		}
		Py_DECREF(slots);
		slots = newslots;

1138
	}
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	if (slots != NULL) {
		/* See if *this* class defines __getstate__ */
		PyObject *getstate = PyDict_GetItemString(dict,
							  "__getstate__");
		if (getstate == NULL) {
			/* If not, provide a bozo that raises TypeError */
			if (bozo_obj == NULL) {
				bozo_obj = PyCFunction_New(&bozo_ml, NULL);
				if (bozo_obj == NULL) {
					/* XXX decref various things */
					return NULL;
				}
			}
			if (PyDict_SetItemString(dict,
						 "__getstate__",
						 bozo_obj) < 0) {
				/* XXX decref various things */
				return NULL;
			}
		}
	}
1160 1161
	if (slots == NULL && base->tp_dictoffset == 0 &&
	    (base->tp_setattro == PyObject_GenericSetAttr ||
1162 1163 1164
	     base->tp_setattro == NULL)) {
		add_dict++;
	}
1165 1166
	if (slots == NULL && base->tp_weaklistoffset == 0 &&
	    base->tp_itemsize == 0) {
1167 1168 1169
		nslots++;
		add_weak++;
	}
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

	/* XXX From here until type is safely allocated,
	   "return NULL" may leak slots! */

	/* Allocate the type object */
	type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
	if (type == NULL)
		return NULL;

	/* Keep name and slots alive in the extended type object */
	et = (etype *)type;
	Py_INCREF(name);
	et->name = name;
	et->slots = slots;

1185
	/* Initialize tp_flags */
1186 1187
	type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
		Py_TPFLAGS_BASETYPE;
1188 1189
	if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
1190 1191 1192 1193 1194 1195 1196 1197

	/* It's a new-style number unless it specifically inherits any
	   old-style numeric behavior */
	if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
	    (base->tp_as_number == NULL))
		type->tp_flags |= Py_TPFLAGS_CHECKTYPES;

	/* Initialize essential fields */
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
	type->tp_as_number = &et->as_number;
	type->tp_as_sequence = &et->as_sequence;
	type->tp_as_mapping = &et->as_mapping;
	type->tp_as_buffer = &et->as_buffer;
	type->tp_name = PyString_AS_STRING(name);

	/* Set tp_base and tp_bases */
	type->tp_bases = bases;
	Py_INCREF(base);
	type->tp_base = base;

1209 1210
	/* Initialize tp_dict from passed-in dict */
	type->tp_dict = dict = PyDict_Copy(dict);
1211 1212 1213 1214 1215
	if (dict == NULL) {
		Py_DECREF(type);
		return NULL;
	}

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	/* Set __module__ in the dict */
	if (PyDict_GetItemString(dict, "__module__") == NULL) {
		tmp = PyEval_GetGlobals();
		if (tmp != NULL) {
			tmp = PyDict_GetItemString(tmp, "__name__");
			if (tmp != NULL) {
				if (PyDict_SetItemString(dict, "__module__",
							 tmp) < 0)
					return NULL;
			}
		}
	}

1229
	/* Set tp_doc to a copy of dict['__doc__'], if the latter is there
1230 1231
	   and is a string.  The __doc__ accessor will first look for tp_doc;
	   if that fails, it will still look into __dict__.
1232 1233 1234 1235 1236
	*/
	{
		PyObject *doc = PyDict_GetItemString(dict, "__doc__");
		if (doc != NULL && PyString_Check(doc)) {
			const size_t n = (size_t)PyString_GET_SIZE(doc);
1237
			type->tp_doc = (char *)PyObject_MALLOC(n+1);
1238 1239 1240 1241 1242 1243 1244 1245
			if (type->tp_doc == NULL) {
				Py_DECREF(type);
				return NULL;
			}
			memcpy(type->tp_doc, PyString_AS_STRING(doc), n+1);
		}
	}

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
	/* Special-case __new__: if it's a plain function,
	   make it a static function */
	tmp = PyDict_GetItemString(dict, "__new__");
	if (tmp != NULL && PyFunction_Check(tmp)) {
		tmp = PyStaticMethod_New(tmp);
		if (tmp == NULL) {
			Py_DECREF(type);
			return NULL;
		}
		PyDict_SetItemString(dict, "__new__", tmp);
		Py_DECREF(tmp);
	}

	/* Add descriptors for custom slots from __slots__, or for __dict__ */
	mp = et->members;
1261
	slotoffset = base->tp_basicsize;
1262 1263 1264 1265
	if (slots != NULL) {
		for (i = 0; i < nslots; i++, mp++) {
			mp->name = PyString_AS_STRING(
				PyTuple_GET_ITEM(slots, i));
1266
			mp->type = T_OBJECT_EX;
1267
			mp->offset = slotoffset;
1268
			if (base->tp_weaklistoffset == 0 &&
1269 1270
			    strcmp(mp->name, "__weakref__") == 0) {
				mp->type = T_OBJECT;
1271
				mp->flags = READONLY;
1272
				type->tp_weaklistoffset = slotoffset;
1273
			}
1274 1275 1276
			slotoffset += sizeof(PyObject *);
		}
	}
1277 1278
	else {
		if (add_dict) {
1279
			if (base->tp_itemsize)
1280 1281
				type->tp_dictoffset =
					-(long)sizeof(PyObject *);
1282 1283
			else
				type->tp_dictoffset = slotoffset;
1284
			slotoffset += sizeof(PyObject *);
1285
			type->tp_getset = subtype_getsets;
1286 1287
		}
		if (add_weak) {
1288
			assert(!base->tp_itemsize);
1289 1290 1291 1292
			type->tp_weaklistoffset = slotoffset;
			mp->name = "__weakref__";
			mp->type = T_OBJECT;
			mp->offset = slotoffset;
1293
			mp->flags = READONLY;
1294 1295 1296
			mp++;
			slotoffset += sizeof(PyObject *);
		}
1297 1298
	}
	type->tp_basicsize = slotoffset;
1299
	type->tp_itemsize = base->tp_itemsize;
1300
	type->tp_members = et->members;
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310

	/* Special case some slots */
	if (type->tp_dictoffset != 0 || nslots > 0) {
		if (base->tp_getattr == NULL && base->tp_getattro == NULL)
			type->tp_getattro = PyObject_GenericGetAttr;
		if (base->tp_setattr == NULL && base->tp_setattro == NULL)
			type->tp_setattro = PyObject_GenericSetAttr;
	}
	type->tp_dealloc = subtype_dealloc;

1311 1312 1313 1314 1315
	/* Enable GC unless there are really no instance variables possible */
	if (!(type->tp_basicsize == sizeof(PyObject) &&
	      type->tp_itemsize == 0))
		type->tp_flags |= Py_TPFLAGS_HAVE_GC;

1316 1317
	/* Always override allocation strategy to use regular heap */
	type->tp_alloc = PyType_GenericAlloc;
1318
	if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
1319
		type->tp_free = PyObject_GC_Del;
1320
		type->tp_traverse = subtype_traverse;
1321
		type->tp_clear = subtype_clear;
1322 1323
	}
	else
1324
		type->tp_free = PyObject_Del;
1325 1326

	/* Initialize the rest */
1327
	if (PyType_Ready(type) < 0) {
1328 1329 1330 1331
		Py_DECREF(type);
		return NULL;
	}

1332 1333
	/* Put the proper slots in place */
	fixup_slot_dispatchers(type);
Guido van Rossum's avatar
Guido van Rossum committed
1334

1335 1336 1337 1338 1339 1340 1341 1342 1343
	return (PyObject *)type;
}

/* Internal API to look for a name through the MRO.
   This returns a borrowed reference, and doesn't set an exception! */
PyObject *
_PyType_Lookup(PyTypeObject *type, PyObject *name)
{
	int i, n;
1344
	PyObject *mro, *res, *base, *dict;
1345

1346
	/* Look in tp_dict of types in MRO */
1347
	mro = type->tp_mro;
1348 1349 1350 1351 1352 1353 1354

	/* If mro is NULL, the type is either not yet initialized
	   by PyType_Ready(), or already cleared by type_clear().
	   Either way the safest thing to do is to return NULL. */
	if (mro == NULL)
		return NULL;

1355 1356 1357
	assert(PyTuple_Check(mro));
	n = PyTuple_GET_SIZE(mro);
	for (i = 0; i < n; i++) {
1358 1359 1360 1361 1362 1363 1364
		base = PyTuple_GET_ITEM(mro, i);
		if (PyClass_Check(base))
			dict = ((PyClassObject *)base)->cl_dict;
		else {
			assert(PyType_Check(base));
			dict = ((PyTypeObject *)base)->tp_dict;
		}
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
		assert(dict && PyDict_Check(dict));
		res = PyDict_GetItem(dict, name);
		if (res != NULL)
			return res;
	}
	return NULL;
}

/* This is similar to PyObject_GenericGetAttr(),
   but uses _PyType_Lookup() instead of just looking in type->tp_dict. */
static PyObject *
type_getattro(PyTypeObject *type, PyObject *name)
{
	PyTypeObject *metatype = type->ob_type;
1379 1380
	PyObject *meta_attribute, *attribute;
	descrgetfunc meta_get;
1381 1382 1383

	/* Initialize this type (we'll assume the metatype is initialized) */
	if (type->tp_dict == NULL) {
1384
		if (PyType_Ready(type) < 0)
1385 1386 1387
			return NULL;
	}

1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
	/* No readable descriptor found yet */
	meta_get = NULL;
		
	/* Look for the attribute in the metatype */
	meta_attribute = _PyType_Lookup(metatype, name);

	if (meta_attribute != NULL) {
		meta_get = meta_attribute->ob_type->tp_descr_get;
				
		if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
			/* Data descriptors implement tp_descr_set to intercept
			 * writes. Assume the attribute is not overridden in
			 * type's tp_dict (and bases): call the descriptor now.
			 */
			return meta_get(meta_attribute, (PyObject *)type,
					(PyObject *)metatype);
		}
1405 1406
	}

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
	/* No data descriptor found on metatype. Look in tp_dict of this
	 * type and its bases */
	attribute = _PyType_Lookup(type, name);
	if (attribute != NULL) {
		/* Implement descriptor functionality, if any */
		descrgetfunc local_get = attribute->ob_type->tp_descr_get;
		if (local_get != NULL) {
			/* NULL 2nd argument indicates the descriptor was
			 * found on the target object itself (or a base)  */
			return local_get(attribute, (PyObject *)NULL,
					 (PyObject *)type);
		}
		
		Py_INCREF(attribute);
		return attribute;
1422 1423
	}

1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
	/* No attribute found in local __dict__ (or bases): use the
	 * descriptor from the metatype, if any */
	if (meta_get != NULL)
		return meta_get(meta_attribute, (PyObject *)type,
				(PyObject *)metatype);

	/* If an ordinary attribute was found on the metatype, return it now */
	if (meta_attribute != NULL) {
		Py_INCREF(meta_attribute);
		return meta_attribute;
1434 1435 1436 1437
	}

	/* Give up */
	PyErr_Format(PyExc_AttributeError,
1438 1439
			 "type object '%.50s' has no attribute '%.400s'",
			 type->tp_name, PyString_AS_STRING(name));
1440 1441 1442 1443 1444 1445
	return NULL;
}

static int
type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
{
1446 1447 1448 1449 1450 1451
	if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
		PyErr_Format(
			PyExc_TypeError,
			"can't set attributes of built-in/extension type '%s'",
			type->tp_name);
		return -1;
1452
	}
1453 1454 1455
	if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
		return -1;
	return update_slot(type, name);
1456 1457 1458 1459 1460 1461 1462 1463 1464
}

static void
type_dealloc(PyTypeObject *type)
{
	etype *et;

	/* Assert this is a heap-allocated type object */
	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1465
	_PyObject_GC_UNTRACK(type);
1466
	PyObject_ClearWeakRefs((PyObject *)type);
1467 1468 1469 1470 1471
	et = (etype *)type;
	Py_XDECREF(type->tp_base);
	Py_XDECREF(type->tp_dict);
	Py_XDECREF(type->tp_bases);
	Py_XDECREF(type->tp_mro);
1472
	Py_XDECREF(type->tp_cache);
1473
	Py_XDECREF(type->tp_subclasses);
1474 1475 1476 1477 1478
	Py_XDECREF(et->name);
	Py_XDECREF(et->slots);
	type->ob_type->tp_free((PyObject *)type);
}

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
static PyObject *
type_subclasses(PyTypeObject *type, PyObject *args_ignored)
{
	PyObject *list, *raw, *ref;
	int i, n;

	list = PyList_New(0);
	if (list == NULL)
		return NULL;
	raw = type->tp_subclasses;
	if (raw == NULL)
		return list;
	assert(PyList_Check(raw));
	n = PyList_GET_SIZE(raw);
	for (i = 0; i < n; i++) {
		ref = PyList_GET_ITEM(raw, i);
1495
		assert(PyWeakref_CheckRef(ref));
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
		ref = PyWeakref_GET_OBJECT(ref);
		if (ref != Py_None) {
			if (PyList_Append(list, ref) < 0) {
				Py_DECREF(list);
				return NULL;
			}
		}
	}
	return list;
}

1507
static PyMethodDef type_methods[] = {
1508
	{"mro", (PyCFunction)mro_external, METH_NOARGS,
1509
	 "mro() -> list\nreturn a type's method resolution order"},
1510 1511
	{"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
	 "__subclasses__() -> list of immediate subclasses"},
1512 1513 1514
	{0}
};

1515
PyDoc_STRVAR(type_doc,
1516
"type(object) -> the object's type\n"
1517
"type(name, bases, dict) -> a new type");
1518

1519 1520 1521 1522 1523
static int
type_traverse(PyTypeObject *type, visitproc visit, void *arg)
{
	int err;

1524 1525 1526
	/* Because of type_is_gc(), the collector only calls this
	   for heaptypes. */
	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1527 1528 1529 1530 1531 1532 1533 1534 1535

#define VISIT(SLOT) \
	if (SLOT) { \
		err = visit((PyObject *)(SLOT), arg); \
		if (err) \
			return err; \
	}

	VISIT(type->tp_dict);
1536
	VISIT(type->tp_cache);
1537 1538 1539
	VISIT(type->tp_mro);
	VISIT(type->tp_bases);
	VISIT(type->tp_base);
1540 1541 1542 1543 1544

	/* There's no need to visit type->tp_subclasses or
	   ((etype *)type)->slots, because they can't be involved
	   in cycles; tp_subclasses is a list of weak references,
	   and slots is a tuple of strings. */
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

#undef VISIT

	return 0;
}

static int
type_clear(PyTypeObject *type)
{
	PyObject *tmp;

1556 1557 1558
	/* Because of type_is_gc(), the collector only calls this
	   for heaptypes. */
	assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
1559 1560 1561 1562 1563 1564 1565 1566

#define CLEAR(SLOT) \
	if (SLOT) { \
		tmp = (PyObject *)(SLOT); \
		SLOT = NULL; \
		Py_DECREF(tmp); \
	}

1567 1568 1569 1570 1571
	/* The only field we need to clear is tp_mro, which is part of a
	   hard cycle (its first element is the class itself) that won't
	   be broken otherwise (it's a tuple and tuples don't have a
	   tp_clear handler).  None of the other fields need to be
	   cleared, and here's why:
1572

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
	   tp_dict:
	       It is a dict, so the collector will call its tp_clear.

	   tp_cache:
	       Not used; if it were, it would be a dict.

	   tp_bases, tp_base:
	       If these are involved in a cycle, there must be at least
	       one other, mutable object in the cycle, e.g. a base
	       class's dict; the cycle will be broken that way.

	   tp_subclasses:
	       A list of weak references can't be part of a cycle; and
	       lists have their own tp_clear.

	   slots (in etype):
	       A tuple of strings can't be part of a cycle.
	*/

	CLEAR(type->tp_mro);
1593

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
#undef CLEAR

	return 0;
}

static int
type_is_gc(PyTypeObject *type)
{
	return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
}

1605 1606
PyTypeObject PyType_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
1607 1608 1609
	0,					/* ob_size */
	"type",					/* tp_name */
	sizeof(etype),				/* tp_basicsize */
1610
	sizeof(PyMemberDef),			/* tp_itemsize */
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
	(destructor)type_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,			 		/* tp_getattr */
	0,					/* tp_setattr */
	type_compare,				/* tp_compare */
	(reprfunc)type_repr,			/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	(hashfunc)_Py_HashPointer,		/* tp_hash */
	(ternaryfunc)type_call,			/* tp_call */
	0,					/* tp_str */
	(getattrofunc)type_getattro,		/* tp_getattro */
	(setattrofunc)type_setattro,		/* tp_setattro */
	0,					/* tp_as_buffer */
1626 1627
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
		Py_TPFLAGS_BASETYPE,		/* tp_flags */
1628
	type_doc,				/* tp_doc */
1629 1630
	(traverseproc)type_traverse,		/* tp_traverse */
	(inquiry)type_clear,			/* tp_clear */
1631
	0,					/* tp_richcompare */
1632
	offsetof(PyTypeObject, tp_weaklist),	/* tp_weaklistoffset */
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
	0,					/* tp_iter */
	0,					/* tp_iternext */
	type_methods,				/* tp_methods */
	type_members,				/* tp_members */
	type_getsets,				/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
	offsetof(PyTypeObject, tp_dict),	/* tp_dictoffset */
	0,					/* tp_init */
	0,					/* tp_alloc */
	type_new,				/* tp_new */
1646
	PyObject_GC_Del,        		/* tp_free */
1647
	(inquiry)type_is_gc,			/* tp_is_gc */
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
};


/* The base type of all types (eventually)... except itself. */

static int
object_init(PyObject *self, PyObject *args, PyObject *kwds)
{
	return 0;
}

static void
object_dealloc(PyObject *self)
{
	self->ob_type->tp_free(self);
}

1665 1666 1667
static PyObject *
object_repr(PyObject *self)
{
1668
	PyTypeObject *type;
1669
	PyObject *mod, *name, *rtn;
1670

1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
	type = self->ob_type;
	mod = type_module(type, NULL);
	if (mod == NULL)
		PyErr_Clear();
	else if (!PyString_Check(mod)) {
		Py_DECREF(mod);
		mod = NULL;
	}
	name = type_name(type, NULL);
	if (name == NULL)
		return NULL;
	if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
1683
		rtn = PyString_FromFormat("<%s.%s object at %p>",
1684 1685 1686
					  PyString_AS_STRING(mod),
					  PyString_AS_STRING(name),
					  self);
1687
	else
1688
		rtn = PyString_FromFormat("<%s object at %p>",
1689
					  type->tp_name, self);
1690 1691
	Py_XDECREF(mod);
	Py_DECREF(name);
1692
	return rtn;
1693 1694
}

1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
static PyObject *
object_str(PyObject *self)
{
	unaryfunc f;

	f = self->ob_type->tp_repr;
	if (f == NULL)
		f = object_repr;
	return f(self);
}

1706 1707 1708 1709 1710 1711
static long
object_hash(PyObject *self)
{
	return _Py_HashPointer(self);
}

1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
static PyObject *
object_get_class(PyObject *self, void *closure)
{
	Py_INCREF(self->ob_type);
	return (PyObject *)(self->ob_type);
}

static int
equiv_structs(PyTypeObject *a, PyTypeObject *b)
{
	return a == b ||
	       (a != NULL &&
		b != NULL &&
		a->tp_basicsize == b->tp_basicsize &&
		a->tp_itemsize == b->tp_itemsize &&
		a->tp_dictoffset == b->tp_dictoffset &&
		a->tp_weaklistoffset == b->tp_weaklistoffset &&
		((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
		 (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
}

static int
same_slots_added(PyTypeObject *a, PyTypeObject *b)
{
	PyTypeObject *base = a->tp_base;
	int size;

	if (base != b->tp_base)
		return 0;
	if (equiv_structs(a, base) && equiv_structs(b, base))
		return 1;
	size = base->tp_basicsize;
	if (a->tp_dictoffset == size && b->tp_dictoffset == size)
		size += sizeof(PyObject *);
	if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
		size += sizeof(PyObject *);
	return size == a->tp_basicsize && size == b->tp_basicsize;
}

static int
object_set_class(PyObject *self, PyObject *value, void *closure)
{
	PyTypeObject *old = self->ob_type;
	PyTypeObject *new, *newbase, *oldbase;

1757 1758 1759 1760 1761
	if (value == NULL) {
		PyErr_SetString(PyExc_TypeError,
				"can't delete __class__ attribute");
		return -1;
	}
1762 1763 1764 1765 1766 1767 1768
	if (!PyType_Check(value)) {
		PyErr_Format(PyExc_TypeError,
		  "__class__ must be set to new-style class, not '%s' object",
		  value->ob_type->tp_name);
		return -1;
	}
	new = (PyTypeObject *)value;
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
	if (new->tp_dealloc != old->tp_dealloc ||
	    new->tp_free != old->tp_free)
	{
		PyErr_Format(PyExc_TypeError,
			     "__class__ assignment: "
			     "'%s' deallocator differs from '%s'",
			     new->tp_name,
			     old->tp_name);
		return -1;
	}
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
	newbase = new;
	oldbase = old;
	while (equiv_structs(newbase, newbase->tp_base))
		newbase = newbase->tp_base;
	while (equiv_structs(oldbase, oldbase->tp_base))
		oldbase = oldbase->tp_base;
	if (newbase != oldbase &&
	    (newbase->tp_base != oldbase->tp_base ||
	     !same_slots_added(newbase, oldbase))) {
		PyErr_Format(PyExc_TypeError,
			     "__class__ assignment: "
			     "'%s' object layout differs from '%s'",
1791
			     new->tp_name,
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
			     old->tp_name);
		return -1;
	}
	if (new->tp_flags & Py_TPFLAGS_HEAPTYPE) {
		Py_INCREF(new);
	}
	self->ob_type = new;
	if (old->tp_flags & Py_TPFLAGS_HEAPTYPE) {
		Py_DECREF(old);
	}
	return 0;
}

static PyGetSetDef object_getsets[] = {
	{"__class__", object_get_class, object_set_class,
	 "the object's class"},
1808 1809 1810
	{0}
};

1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
static PyObject *
object_reduce(PyObject *self, PyObject *args)
{
	/* Call copy_reg._reduce(self) */
	static PyObject *copy_reg_str;
	PyObject *copy_reg, *res;

	if (!copy_reg_str) {
		copy_reg_str = PyString_InternFromString("copy_reg");
		if (copy_reg_str == NULL)
			return NULL;
	}
	copy_reg = PyImport_Import(copy_reg_str);
	if (!copy_reg)
		return NULL;
	res = PyEval_CallMethod(copy_reg, "_reduce", "(O)", self);
	Py_DECREF(copy_reg);
	return res;
}

static PyMethodDef object_methods[] = {
	{"__reduce__", object_reduce, METH_NOARGS, "helper for pickle"},
	{0}
};

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
PyTypeObject PyBaseObject_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
 	0,					/* ob_size */
	"object",				/* tp_name */
	sizeof(PyObject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	(destructor)object_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,			 		/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
1847
	object_repr,				/* tp_repr */
1848 1849 1850
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
1851
	object_hash,				/* tp_hash */
1852
	0,					/* tp_call */
1853
	object_str,				/* tp_str */
1854
	PyObject_GenericGetAttr,		/* tp_getattro */
1855
	PyObject_GenericSetAttr,		/* tp_setattro */
1856 1857 1858 1859 1860 1861 1862 1863 1864
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
	"The most base type",			/* tp_doc */
	0,					/* tp_traverse */
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
1865
	object_methods,				/* tp_methods */
1866 1867
	0,					/* tp_members */
	object_getsets,				/* tp_getset */
1868 1869 1870 1871 1872 1873 1874
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
	object_init,				/* tp_init */
	PyType_GenericAlloc,			/* tp_alloc */
1875
	PyType_GenericNew,			/* tp_new */
1876
	PyObject_Del,           		/* tp_free */
Guido van Rossum's avatar
Guido van Rossum committed
1877
};
1878 1879 1880 1881


/* Initialize the __dict__ in a type object */

1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
static PyObject *
create_specialmethod(PyMethodDef *meth, PyObject *(*func)(PyObject *))
{
	PyObject *cfunc;
	PyObject *result;

	cfunc = PyCFunction_New(meth, NULL);
	if (cfunc == NULL)
		return NULL;
	result = func(cfunc);
	Py_DECREF(cfunc);
	return result;
}

1896 1897 1898
static int
add_methods(PyTypeObject *type, PyMethodDef *meth)
{
1899
	PyObject *dict = type->tp_dict;
1900 1901 1902 1903 1904

	for (; meth->ml_name != NULL; meth++) {
		PyObject *descr;
		if (PyDict_GetItemString(dict, meth->ml_name))
			continue;
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
		if (meth->ml_flags & METH_CLASS) {
			if (meth->ml_flags & METH_STATIC) {
				PyErr_SetString(PyExc_ValueError,
				     "method cannot be both class and static");
				return -1;
			}
			descr = create_specialmethod(meth, PyClassMethod_New);
		}
		else if (meth->ml_flags & METH_STATIC) {
			descr = create_specialmethod(meth, PyStaticMethod_New);
		}
		else {
			descr = PyDescr_NewMethod(type, meth);
		}
1919 1920
		if (descr == NULL)
			return -1;
1921
		if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
1922 1923 1924 1925 1926 1927 1928
			return -1;
		Py_DECREF(descr);
	}
	return 0;
}

static int
1929
add_members(PyTypeObject *type, PyMemberDef *memb)
1930
{
1931
	PyObject *dict = type->tp_dict;
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947

	for (; memb->name != NULL; memb++) {
		PyObject *descr;
		if (PyDict_GetItemString(dict, memb->name))
			continue;
		descr = PyDescr_NewMember(type, memb);
		if (descr == NULL)
			return -1;
		if (PyDict_SetItemString(dict, memb->name, descr) < 0)
			return -1;
		Py_DECREF(descr);
	}
	return 0;
}

static int
1948
add_getset(PyTypeObject *type, PyGetSetDef *gsp)
1949
{
1950
	PyObject *dict = type->tp_dict;
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966

	for (; gsp->name != NULL; gsp++) {
		PyObject *descr;
		if (PyDict_GetItemString(dict, gsp->name))
			continue;
		descr = PyDescr_NewGetSet(type, gsp);

		if (descr == NULL)
			return -1;
		if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
			return -1;
		Py_DECREF(descr);
	}
	return 0;
}

1967 1968 1969 1970
static void
inherit_special(PyTypeObject *type, PyTypeObject *base)
{
	int oldsize, newsize;
1971

1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
	/* Special flag magic */
	if (!type->tp_as_buffer && base->tp_as_buffer) {
		type->tp_flags &= ~Py_TPFLAGS_HAVE_GETCHARBUFFER;
		type->tp_flags |=
			base->tp_flags & Py_TPFLAGS_HAVE_GETCHARBUFFER;
	}
	if (!type->tp_as_sequence && base->tp_as_sequence) {
		type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
		type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
	}
	if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
	    (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
		if ((!type->tp_as_number && base->tp_as_number) ||
		    (!type->tp_as_sequence && base->tp_as_sequence)) {
			type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
			if (!type->tp_as_number && !type->tp_as_sequence) {
				type->tp_flags |= base->tp_flags &
					Py_TPFLAGS_HAVE_INPLACEOPS;
			}
		}
		/* Wow */
	}
	if (!type->tp_as_number && base->tp_as_number) {
		type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
		type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
	}

	/* Copying basicsize is connected to the GC flags */
2000 2001 2002 2003
	oldsize = base->tp_basicsize;
	newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
	if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
	    (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
2004 2005
	    (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
	    (!type->tp_traverse && !type->tp_clear)) {
2006
		type->tp_flags |= Py_TPFLAGS_HAVE_GC;
2007 2008 2009 2010 2011 2012
		if (type->tp_traverse == NULL)
			type->tp_traverse = base->tp_traverse;
		if (type->tp_clear == NULL)
			type->tp_clear = base->tp_clear;
	}
	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
		/* The condition below could use some explanation.
		   It appears that tp_new is not inherited for static types
		   whose base class is 'object'; this seems to be a precaution
		   so that old extension types don't suddenly become
		   callable (object.__new__ wouldn't insure the invariants
		   that the extension type's own factory function ensures).
		   Heap types, of course, are under our control, so they do
		   inherit tp_new; static extension types that specify some
		   other built-in type as the default are considered
		   new-style-aware so they also inherit object.__new__. */
2023 2024 2025 2026 2027 2028
		if (base != &PyBaseObject_Type ||
		    (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
			if (type->tp_new == NULL)
				type->tp_new = base->tp_new;
		}
	}
2029
	type->tp_basicsize = newsize;
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043

	/* Copy other non-function slots */

#undef COPYVAL
#define COPYVAL(SLOT) \
	if (type->SLOT == 0) type->SLOT = base->SLOT

	COPYVAL(tp_itemsize);
	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
		COPYVAL(tp_weaklistoffset);
	}
	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
		COPYVAL(tp_dictoffset);
	}
2044 2045 2046
}

static void
2047 2048
inherit_slots(PyTypeObject *type, PyTypeObject *base)
{
2049
	PyTypeObject *basebase;
2050

2051
#undef SLOTDEFINED
2052 2053 2054 2055
#undef COPYSLOT
#undef COPYNUM
#undef COPYSEQ
#undef COPYMAP
2056
#undef COPYBUF
2057 2058 2059 2060 2061

#define SLOTDEFINED(SLOT) \
	(base->SLOT != 0 && \
	 (basebase == NULL || base->SLOT != basebase->SLOT))

2062
#define COPYSLOT(SLOT) \
2063
	if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
2064 2065 2066 2067

#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
2068
#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
2069

2070 2071 2072 2073 2074 2075 2076
	/* This won't inherit indirect slots (from tp_as_number etc.)
	   if type doesn't provide the space. */

	if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
		basebase = base->tp_base;
		if (basebase->tp_as_number == NULL)
			basebase = NULL;
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
		COPYNUM(nb_add);
		COPYNUM(nb_subtract);
		COPYNUM(nb_multiply);
		COPYNUM(nb_divide);
		COPYNUM(nb_remainder);
		COPYNUM(nb_divmod);
		COPYNUM(nb_power);
		COPYNUM(nb_negative);
		COPYNUM(nb_positive);
		COPYNUM(nb_absolute);
		COPYNUM(nb_nonzero);
		COPYNUM(nb_invert);
		COPYNUM(nb_lshift);
		COPYNUM(nb_rshift);
		COPYNUM(nb_and);
		COPYNUM(nb_xor);
		COPYNUM(nb_or);
		COPYNUM(nb_coerce);
		COPYNUM(nb_int);
		COPYNUM(nb_long);
		COPYNUM(nb_float);
		COPYNUM(nb_oct);
		COPYNUM(nb_hex);
		COPYNUM(nb_inplace_add);
		COPYNUM(nb_inplace_subtract);
		COPYNUM(nb_inplace_multiply);
		COPYNUM(nb_inplace_divide);
		COPYNUM(nb_inplace_remainder);
		COPYNUM(nb_inplace_power);
		COPYNUM(nb_inplace_lshift);
		COPYNUM(nb_inplace_rshift);
		COPYNUM(nb_inplace_and);
		COPYNUM(nb_inplace_xor);
		COPYNUM(nb_inplace_or);
2111 2112 2113 2114 2115 2116
		if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
			COPYNUM(nb_true_divide);
			COPYNUM(nb_floor_divide);
			COPYNUM(nb_inplace_true_divide);
			COPYNUM(nb_inplace_floor_divide);
		}
2117 2118
	}

2119 2120 2121 2122
	if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
		basebase = base->tp_base;
		if (basebase->tp_as_sequence == NULL)
			basebase = NULL;
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
		COPYSEQ(sq_length);
		COPYSEQ(sq_concat);
		COPYSEQ(sq_repeat);
		COPYSEQ(sq_item);
		COPYSEQ(sq_slice);
		COPYSEQ(sq_ass_item);
		COPYSEQ(sq_ass_slice);
		COPYSEQ(sq_contains);
		COPYSEQ(sq_inplace_concat);
		COPYSEQ(sq_inplace_repeat);
	}

2135 2136 2137 2138
	if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
		basebase = base->tp_base;
		if (basebase->tp_as_mapping == NULL)
			basebase = NULL;
2139 2140 2141 2142 2143
		COPYMAP(mp_length);
		COPYMAP(mp_subscript);
		COPYMAP(mp_ass_subscript);
	}

2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
	if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
		basebase = base->tp_base;
		if (basebase->tp_as_buffer == NULL)
			basebase = NULL;
		COPYBUF(bf_getreadbuffer);
		COPYBUF(bf_getwritebuffer);
		COPYBUF(bf_getsegcount);
		COPYBUF(bf_getcharbuffer);
	}

2154
	basebase = base->tp_base;
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167

	COPYSLOT(tp_dealloc);
	COPYSLOT(tp_print);
	if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
		type->tp_getattr = base->tp_getattr;
		type->tp_getattro = base->tp_getattro;
	}
	if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
		type->tp_setattr = base->tp_setattr;
		type->tp_setattro = base->tp_setattro;
	}
	/* tp_compare see tp_richcompare */
	COPYSLOT(tp_repr);
2168
	/* tp_hash see tp_richcompare */
2169 2170 2171
	COPYSLOT(tp_call);
	COPYSLOT(tp_str);
	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
2172 2173 2174 2175
		if (type->tp_compare == NULL &&
		    type->tp_richcompare == NULL &&
		    type->tp_hash == NULL)
		{
2176 2177
			type->tp_compare = base->tp_compare;
			type->tp_richcompare = base->tp_richcompare;
2178
			type->tp_hash = base->tp_hash;
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
		}
	}
	else {
		COPYSLOT(tp_compare);
	}
	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
		COPYSLOT(tp_iter);
		COPYSLOT(tp_iternext);
	}
	if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
		COPYSLOT(tp_descr_get);
		COPYSLOT(tp_descr_set);
		COPYSLOT(tp_dictoffset);
		COPYSLOT(tp_init);
		COPYSLOT(tp_alloc);
		COPYSLOT(tp_free);
2195
		COPYSLOT(tp_is_gc);
2196 2197 2198
	}
}

2199
staticforward int add_operators(PyTypeObject *);
2200
staticforward int add_subclass(PyTypeObject *base, PyTypeObject *type);
2201

2202
int
2203
PyType_Ready(PyTypeObject *type)
2204
{
2205
	PyObject *dict, *bases;
2206 2207 2208
	PyTypeObject *base;
	int i, n;

2209 2210
	if (type->tp_flags & Py_TPFLAGS_READY) {
		assert(type->tp_dict != NULL);
2211
		return 0;
2212
	}
2213 2214 2215
	assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);

	type->tp_flags |= Py_TPFLAGS_READYING;
2216 2217 2218 2219 2220 2221

	/* Initialize tp_base (defaults to BaseObject unless that's us) */
	base = type->tp_base;
	if (base == NULL && type != &PyBaseObject_Type)
		base = type->tp_base = &PyBaseObject_Type;

2222 2223 2224 2225 2226 2227
	/* Initialize ob_type if NULL.  This means extensions that want to be
	   compilable separately on Windows can call PyType_Ready() instead of
	   initializing the ob_type field of their type objects. */
	if (type->ob_type == NULL)
		type->ob_type = base->ob_type;

2228 2229 2230 2231 2232 2233 2234 2235
	/* Initialize tp_bases */
	bases = type->tp_bases;
	if (bases == NULL) {
		if (base == NULL)
			bases = PyTuple_New(0);
		else
			bases = Py_BuildValue("(O)", base);
		if (bases == NULL)
2236
			goto error;
2237 2238 2239 2240
		type->tp_bases = bases;
	}

	/* Initialize the base class */
2241
	if (base && base->tp_dict == NULL) {
2242
		if (PyType_Ready(base) < 0)
2243
			goto error;
2244 2245
	}

2246 2247
	/* Initialize tp_dict */
	dict = type->tp_dict;
2248 2249 2250
	if (dict == NULL) {
		dict = PyDict_New();
		if (dict == NULL)
2251
			goto error;
2252
		type->tp_dict = dict;
2253 2254
	}

2255
	/* Add type-specific descriptors to tp_dict */
2256
	if (add_operators(type) < 0)
2257
		goto error;
2258 2259
	if (type->tp_methods != NULL) {
		if (add_methods(type, type->tp_methods) < 0)
2260
			goto error;
2261 2262 2263
	}
	if (type->tp_members != NULL) {
		if (add_members(type, type->tp_members) < 0)
2264
			goto error;
2265 2266 2267
	}
	if (type->tp_getset != NULL) {
		if (add_getset(type, type->tp_getset) < 0)
2268
			goto error;
2269 2270 2271 2272
	}

	/* Calculate method resolution order */
	if (mro_internal(type) < 0) {
2273
		goto error;
2274 2275
	}

2276 2277 2278 2279
	/* Inherit special flags from dominant base */
	if (type->tp_base != NULL)
		inherit_special(type, type->tp_base);

2280
	/* Initialize tp_dict properly */
2281 2282 2283 2284 2285
	bases = type->tp_mro;
	assert(bases != NULL);
	assert(PyTuple_Check(bases));
	n = PyTuple_GET_SIZE(bases);
	for (i = 1; i < n; i++) {
2286 2287 2288
		PyObject *b = PyTuple_GET_ITEM(bases, i);
		if (PyType_Check(b))
			inherit_slots(type, (PyTypeObject *)b);
2289
	}
2290

2291 2292 2293 2294 2295 2296 2297 2298 2299
	/* if the type dictionary doesn't contain a __doc__, set it from
	   the tp_doc slot.
	 */
	if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
		if (type->tp_doc != NULL) {
			PyObject *doc = PyString_FromString(type->tp_doc);
			PyDict_SetItemString(type->tp_dict, "__doc__", doc);
			Py_DECREF(doc);
		} else {
2300 2301
			PyDict_SetItemString(type->tp_dict,
					     "__doc__", Py_None);
2302 2303 2304
		}
	}

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
	/* Some more special stuff */
	base = type->tp_base;
	if (base != NULL) {
		if (type->tp_as_number == NULL)
			type->tp_as_number = base->tp_as_number;
		if (type->tp_as_sequence == NULL)
			type->tp_as_sequence = base->tp_as_sequence;
		if (type->tp_as_mapping == NULL)
			type->tp_as_mapping = base->tp_as_mapping;
	}
2315

2316 2317 2318 2319
	/* Link into each base class's list of subclasses */
	bases = type->tp_bases;
	n = PyTuple_GET_SIZE(bases);
	for (i = 0; i < n; i++) {
2320 2321 2322
		PyObject *b = PyTuple_GET_ITEM(bases, i);
		if (PyType_Check(b) &&
		    add_subclass((PyTypeObject *)b, type) < 0)
2323 2324 2325
			goto error;
	}

2326
	/* All done -- set the ready flag */
2327 2328 2329
	assert(type->tp_dict != NULL);
	type->tp_flags =
		(type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
2330
	return 0;
2331 2332 2333 2334

  error:
	type->tp_flags &= ~Py_TPFLAGS_READYING;
	return -1;
2335 2336
}

2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
static int
add_subclass(PyTypeObject *base, PyTypeObject *type)
{
	int i;
	PyObject *list, *ref, *new;

	list = base->tp_subclasses;
	if (list == NULL) {
		base->tp_subclasses = list = PyList_New(0);
		if (list == NULL)
			return -1;
	}
	assert(PyList_Check(list));
	new = PyWeakref_NewRef((PyObject *)type, NULL);
	i = PyList_GET_SIZE(list);
	while (--i >= 0) {
		ref = PyList_GET_ITEM(list, i);
		assert(PyWeakref_CheckRef(ref));
		if (PyWeakref_GET_OBJECT(ref) == Py_None)
			return PyList_SetItem(list, i, new);
	}
	i = PyList_Append(list, new);
	Py_DECREF(new);
	return i;
}

2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396

/* Generic wrappers for overloadable 'operators' such as __getitem__ */

/* There's a wrapper *function* for each distinct function typedef used
   for type object slots (e.g. binaryfunc, ternaryfunc, etc.).  There's a
   wrapper *table* for each distinct operation (e.g. __len__, __add__).
   Most tables have only one entry; the tables for binary operators have two
   entries, one regular and one with reversed arguments. */

static PyObject *
wrap_inquiry(PyObject *self, PyObject *args, void *wrapped)
{
	inquiry func = (inquiry)wrapped;
	int res;

	if (!PyArg_ParseTuple(args, ""))
		return NULL;
	res = (*func)(self);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	return PyInt_FromLong((long)res);
}

static PyObject *
wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
{
	binaryfunc func = (binaryfunc)wrapped;
	PyObject *other;

	if (!PyArg_ParseTuple(args, "O", &other))
		return NULL;
	return (*func)(self, other);
}

2397 2398 2399 2400 2401 2402 2403 2404 2405
static PyObject *
wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
{
	binaryfunc func = (binaryfunc)wrapped;
	PyObject *other;

	if (!PyArg_ParseTuple(args, "O", &other))
		return NULL;
	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2406
	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2407 2408 2409 2410 2411 2412
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	return (*func)(self, other);
}

2413 2414 2415 2416 2417 2418 2419 2420
static PyObject *
wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
{
	binaryfunc func = (binaryfunc)wrapped;
	PyObject *other;

	if (!PyArg_ParseTuple(args, "O", &other))
		return NULL;
2421
	if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
2422
	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2423 2424 2425
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
2426 2427 2428
	return (*func)(other, self);
}

2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
static PyObject *
wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
{
	coercion func = (coercion)wrapped;
	PyObject *other, *res;
	int ok;

	if (!PyArg_ParseTuple(args, "O", &other))
		return NULL;
	ok = func(&self, &other);
	if (ok < 0)
		return NULL;
	if (ok > 0) {
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	res = PyTuple_New(2);
	if (res == NULL) {
		Py_DECREF(self);
		Py_DECREF(other);
		return NULL;
	}
	PyTuple_SET_ITEM(res, 0, self);
	PyTuple_SET_ITEM(res, 1, other);
	return res;
}

2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
static PyObject *
wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
{
	ternaryfunc func = (ternaryfunc)wrapped;
	PyObject *other;
	PyObject *third = Py_None;

	/* Note: This wrapper only works for __pow__() */

	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
		return NULL;
	return (*func)(self, other, third);
}

2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
static PyObject *
wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
{
	ternaryfunc func = (ternaryfunc)wrapped;
	PyObject *other;
	PyObject *third = Py_None;

	/* Note: This wrapper only works for __pow__() */

	if (!PyArg_ParseTuple(args, "O|O", &other, &third))
		return NULL;
	return (*func)(other, self, third);
}

2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
static PyObject *
wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
{
	unaryfunc func = (unaryfunc)wrapped;

	if (!PyArg_ParseTuple(args, ""))
		return NULL;
	return (*func)(self);
}

static PyObject *
wrap_intargfunc(PyObject *self, PyObject *args, void *wrapped)
{
	intargfunc func = (intargfunc)wrapped;
	int i;

	if (!PyArg_ParseTuple(args, "i", &i))
		return NULL;
	return (*func)(self, i);
}

2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
static int
getindex(PyObject *self, PyObject *arg)
{
	int i;

	i = PyInt_AsLong(arg);
	if (i == -1 && PyErr_Occurred())
		return -1;
	if (i < 0) {
		PySequenceMethods *sq = self->ob_type->tp_as_sequence;
		if (sq && sq->sq_length) {
			int n = (*sq->sq_length)(self);
			if (n < 0)
				return -1;
			i += n;
		}
	}
	return i;
}

static PyObject *
wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
{
	intargfunc func = (intargfunc)wrapped;
	PyObject *arg;
	int i;

2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
	if (PyTuple_GET_SIZE(args) == 1) {
		arg = PyTuple_GET_ITEM(args, 0);
		i = getindex(self, arg);
		if (i == -1 && PyErr_Occurred())
			return NULL;
		return (*func)(self, i);
	}
	PyArg_ParseTuple(args, "O", &arg);
	assert(PyErr_Occurred());
	return NULL;
2542 2543
}

2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
static PyObject *
wrap_intintargfunc(PyObject *self, PyObject *args, void *wrapped)
{
	intintargfunc func = (intintargfunc)wrapped;
	int i, j;

	if (!PyArg_ParseTuple(args, "ii", &i, &j))
		return NULL;
	return (*func)(self, i, j);
}

static PyObject *
2556
wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
2557 2558 2559
{
	intobjargproc func = (intobjargproc)wrapped;
	int i, res;
2560
	PyObject *arg, *value;
2561

2562 2563 2564 2565
	if (!PyArg_ParseTuple(args, "OO", &arg, &value))
		return NULL;
	i = getindex(self, arg);
	if (i == -1 && PyErr_Occurred())
2566 2567 2568 2569 2570 2571 2572 2573
		return NULL;
	res = (*func)(self, i, value);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

2574
static PyObject *
2575
wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
2576 2577 2578
{
	intobjargproc func = (intobjargproc)wrapped;
	int i, res;
2579
	PyObject *arg;
2580

2581 2582 2583 2584
	if (!PyArg_ParseTuple(args, "O", &arg))
		return NULL;
	i = getindex(self, arg);
	if (i == -1 && PyErr_Occurred())
2585 2586 2587 2588 2589 2590 2591 2592
		return NULL;
	res = (*func)(self, i, NULL);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
static PyObject *
wrap_intintobjargproc(PyObject *self, PyObject *args, void *wrapped)
{
	intintobjargproc func = (intintobjargproc)wrapped;
	int i, j, res;
	PyObject *value;

	if (!PyArg_ParseTuple(args, "iiO", &i, &j, &value))
		return NULL;
	res = (*func)(self, i, j, value);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
static PyObject *
wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
{
	intintobjargproc func = (intintobjargproc)wrapped;
	int i, j, res;

	if (!PyArg_ParseTuple(args, "ii", &i, &j))
		return NULL;
	res = (*func)(self, i, j, NULL);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
/* XXX objobjproc is a misnomer; should be objargpred */
static PyObject *
wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
{
	objobjproc func = (objobjproc)wrapped;
	int res;
	PyObject *value;

	if (!PyArg_ParseTuple(args, "O", &value))
		return NULL;
	res = (*func)(self, value);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	return PyInt_FromLong((long)res);
}

static PyObject *
wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
{
	objobjargproc func = (objobjargproc)wrapped;
	int res;
	PyObject *key, *value;

	if (!PyArg_ParseTuple(args, "OO", &key, &value))
		return NULL;
	res = (*func)(self, key, value);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
static PyObject *
wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
{
	objobjargproc func = (objobjargproc)wrapped;
	int res;
	PyObject *key;

	if (!PyArg_ParseTuple(args, "O", &key))
		return NULL;
	res = (*func)(self, key, NULL);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

2672 2673 2674 2675 2676 2677 2678 2679 2680
static PyObject *
wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
{
	cmpfunc func = (cmpfunc)wrapped;
	int res;
	PyObject *other;

	if (!PyArg_ParseTuple(args, "O", &other))
		return NULL;
2681 2682
	if (other->ob_type->tp_compare != func &&
	    !PyType_IsSubtype(other->ob_type, self->ob_type)) {
2683 2684 2685 2686 2687 2688 2689 2690
		PyErr_Format(
			PyExc_TypeError,
			"%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
			self->ob_type->tp_name,
			self->ob_type->tp_name,
			other->ob_type->tp_name);
		return NULL;
	}
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
	res = (*func)(self, other);
	if (PyErr_Occurred())
		return NULL;
	return PyInt_FromLong((long)res);
}

static PyObject *
wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
{
	setattrofunc func = (setattrofunc)wrapped;
	int res;
	PyObject *name, *value;

	if (!PyArg_ParseTuple(args, "OO", &name, &value))
		return NULL;
	res = (*func)(self, name, value);
	if (res < 0)
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

static PyObject *
wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
{
	setattrofunc func = (setattrofunc)wrapped;
	int res;
	PyObject *name;

	if (!PyArg_ParseTuple(args, "O", &name))
		return NULL;
	res = (*func)(self, name, NULL);
	if (res < 0)
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

static PyObject *
wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
{
	hashfunc func = (hashfunc)wrapped;
	long res;

	if (!PyArg_ParseTuple(args, ""))
		return NULL;
	res = (*func)(self);
	if (res == -1 && PyErr_Occurred())
		return NULL;
	return PyInt_FromLong(res);
}

static PyObject *
2744
wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
2745 2746 2747
{
	ternaryfunc func = (ternaryfunc)wrapped;

2748
	return (*func)(self, args, kwds);
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
}

static PyObject *
wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
{
	richcmpfunc func = (richcmpfunc)wrapped;
	PyObject *other;

	if (!PyArg_ParseTuple(args, "O", &other))
		return NULL;
	return (*func)(self, other, op);
}

#undef RICHCMP_WRAPPER
#define RICHCMP_WRAPPER(NAME, OP) \
static PyObject * \
richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
{ \
	return wrap_richcmpfunc(self, args, wrapped, OP); \
}

2770 2771 2772 2773 2774 2775
RICHCMP_WRAPPER(lt, Py_LT)
RICHCMP_WRAPPER(le, Py_LE)
RICHCMP_WRAPPER(eq, Py_EQ)
RICHCMP_WRAPPER(ne, Py_NE)
RICHCMP_WRAPPER(gt, Py_GT)
RICHCMP_WRAPPER(ge, Py_GE)
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803

static PyObject *
wrap_next(PyObject *self, PyObject *args, void *wrapped)
{
	unaryfunc func = (unaryfunc)wrapped;
	PyObject *res;

	if (!PyArg_ParseTuple(args, ""))
		return NULL;
	res = (*func)(self);
	if (res == NULL && !PyErr_Occurred())
		PyErr_SetNone(PyExc_StopIteration);
	return res;
}

static PyObject *
wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
{
	descrgetfunc func = (descrgetfunc)wrapped;
	PyObject *obj;
	PyObject *type = NULL;

	if (!PyArg_ParseTuple(args, "O|O", &obj, &type))
		return NULL;
	return (*func)(self, obj, type);
}

static PyObject *
2804
wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
{
	descrsetfunc func = (descrsetfunc)wrapped;
	PyObject *obj, *value;
	int ret;

	if (!PyArg_ParseTuple(args, "OO", &obj, &value))
		return NULL;
	ret = (*func)(self, obj, value);
	if (ret < 0)
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

static PyObject *
2820
wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
2821 2822 2823
{
	initproc func = (initproc)wrapped;

2824
	if (func(self, args, kwds) < 0)
2825 2826 2827 2828 2829 2830
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

static PyObject *
2831
tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
2832
{
2833
	PyTypeObject *type, *subtype, *staticbase;
2834 2835 2836 2837 2838 2839
	PyObject *arg0, *res;

	if (self == NULL || !PyType_Check(self))
		Py_FatalError("__new__() called with non-type 'self'");
	type = (PyTypeObject *)self;
	if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
2840 2841 2842
		PyErr_Format(PyExc_TypeError,
			     "%s.__new__(): not enough arguments",
			     type->tp_name);
2843 2844 2845 2846
		return NULL;
	}
	arg0 = PyTuple_GET_ITEM(args, 0);
	if (!PyType_Check(arg0)) {
2847 2848 2849 2850
		PyErr_Format(PyExc_TypeError,
			     "%s.__new__(X): X is not a type object (%s)",
			     type->tp_name,
			     arg0->ob_type->tp_name);
2851 2852 2853 2854
		return NULL;
	}
	subtype = (PyTypeObject *)arg0;
	if (!PyType_IsSubtype(subtype, type)) {
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
		PyErr_Format(PyExc_TypeError,
			     "%s.__new__(%s): %s is not a subtype of %s",
			     type->tp_name,
			     subtype->tp_name,
			     subtype->tp_name,
			     type->tp_name);
		return NULL;
	}

	/* Check that the use doesn't do something silly and unsafe like
2865
	   object.__new__(dict).  To do this, we check that the
2866 2867 2868 2869
	   most derived base that's not a heap type is this type. */
	staticbase = subtype;
	while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
		staticbase = staticbase->tp_base;
2870
	if (staticbase->tp_new != type->tp_new) {
2871 2872 2873 2874 2875
		PyErr_Format(PyExc_TypeError,
			     "%s.__new__(%s) is not safe, use %s.__new__()",
			     type->tp_name,
			     subtype->tp_name,
			     staticbase == NULL ? "?" : staticbase->tp_name);
2876 2877
		return NULL;
	}
2878

2879 2880 2881 2882 2883 2884
	args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
	if (args == NULL)
		return NULL;
	res = type->tp_new(subtype, args, kwds);
	Py_DECREF(args);
	return res;
2885 2886
}

2887 2888 2889
static struct PyMethodDef tp_new_methoddef[] = {
	{"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
	 "T.__new__(S, ...) -> a new object with type S, a subtype of T"},
2890 2891 2892
	{0}
};

2893 2894 2895
static int
add_tp_new_wrapper(PyTypeObject *type)
{
Guido van Rossum's avatar
Guido van Rossum committed
2896
	PyObject *func;
2897

2898
	if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
Guido van Rossum's avatar
Guido van Rossum committed
2899 2900
		return 0;
	func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
2901 2902
	if (func == NULL)
		return -1;
2903
	return PyDict_SetItemString(type->tp_dict, "__new__", func);
2904 2905
}

Guido van Rossum's avatar
Guido van Rossum committed
2906 2907
/* Slot wrappers that call the corresponding __foo__ slot.  See comments
   below at override_slots() for more explanation. */
2908

2909
#define SLOT0(FUNCNAME, OPSTR) \
2910
static PyObject * \
2911
FUNCNAME(PyObject *self) \
2912
{ \
2913
	static PyObject *cache_str; \
Guido van Rossum's avatar
Guido van Rossum committed
2914
	return call_method(self, OPSTR, &cache_str, "()"); \
2915 2916
}

2917
#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
2918
static PyObject * \
2919
FUNCNAME(PyObject *self, ARG1TYPE arg1) \
2920
{ \
2921
	static PyObject *cache_str; \
Guido van Rossum's avatar
Guido van Rossum committed
2922
	return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
2923 2924
}

2925 2926 2927 2928 2929

#define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \
static PyObject * \
FUNCNAME(PyObject *self, PyObject *other) \
{ \
2930
	static PyObject *cache_str, *rcache_str; \
2931 2932 2933
	int do_other = self->ob_type != other->ob_type && \
	    other->ob_type->tp_as_number != NULL && \
	    other->ob_type->tp_as_number->SLOTNAME == TESTFUNC; \
2934 2935 2936
	if (self->ob_type->tp_as_number != NULL && \
	    self->ob_type->tp_as_number->SLOTNAME == TESTFUNC) { \
		PyObject *r; \
2937 2938 2939 2940 2941 2942 2943 2944 2945
		if (do_other && \
		    PyType_IsSubtype(other->ob_type, self->ob_type)) { \
			r = call_maybe( \
				other, ROPSTR, &rcache_str, "(O)", self); \
			if (r != Py_NotImplemented) \
				return r; \
			Py_DECREF(r); \
			do_other = 0; \
		} \
2946
		r = call_maybe( \
Guido van Rossum's avatar
Guido van Rossum committed
2947
			self, OPSTR, &cache_str, "(O)", other); \
2948 2949 2950 2951 2952
		if (r != Py_NotImplemented || \
		    other->ob_type == self->ob_type) \
			return r; \
		Py_DECREF(r); \
	} \
2953
	if (do_other) { \
2954
		return call_maybe( \
Guido van Rossum's avatar
Guido van Rossum committed
2955
			other, ROPSTR, &rcache_str, "(O)", self); \
2956 2957 2958 2959 2960 2961 2962 2963 2964
	} \
	Py_INCREF(Py_NotImplemented); \
	return Py_NotImplemented; \
}

#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
	SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)

#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
2965
static PyObject * \
2966
FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
2967
{ \
2968
	static PyObject *cache_str; \
Guido van Rossum's avatar
Guido van Rossum committed
2969 2970
	return call_method(self, OPSTR, &cache_str, \
			   "(" ARGCODES ")", arg1, arg2); \
2971 2972 2973 2974 2975
}

static int
slot_sq_length(PyObject *self)
{
2976
	static PyObject *len_str;
Guido van Rossum's avatar
Guido van Rossum committed
2977
	PyObject *res = call_method(self, "__len__", &len_str, "()");
2978
	int len;
2979 2980 2981

	if (res == NULL)
		return -1;
2982 2983 2984
	len = (int)PyInt_AsLong(res);
	Py_DECREF(res);
	return len;
2985 2986
}

2987 2988
SLOT1(slot_sq_concat, "__add__", PyObject *, "O")
SLOT1(slot_sq_repeat, "__mul__", int, "i")
2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030

/* Super-optimized version of slot_sq_item.
   Other slots could do the same... */
static PyObject *
slot_sq_item(PyObject *self, int i)
{
	static PyObject *getitem_str;
	PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
	descrgetfunc f;

	if (getitem_str == NULL) {
		getitem_str = PyString_InternFromString("__getitem__");
		if (getitem_str == NULL)
			return NULL;
	}
	func = _PyType_Lookup(self->ob_type, getitem_str);
	if (func != NULL) {
		if ((f = func->ob_type->tp_descr_get) == NULL)
			Py_INCREF(func);
		else
			func = f(func, self, (PyObject *)(self->ob_type));
		ival = PyInt_FromLong(i);
		if (ival != NULL) {
			args = PyTuple_New(1);
			if (args != NULL) {
				PyTuple_SET_ITEM(args, 0, ival);
				retval = PyObject_Call(func, args, NULL);
				Py_XDECREF(args);
				Py_XDECREF(func);
				return retval;
			}
		}
	}
	else {
		PyErr_SetObject(PyExc_AttributeError, getitem_str);
	}
	Py_XDECREF(args);
	Py_XDECREF(ival);
	Py_XDECREF(func);
	return NULL;
}

3031
SLOT2(slot_sq_slice, "__getslice__", int, int, "ii")
3032 3033 3034 3035 3036

static int
slot_sq_ass_item(PyObject *self, int index, PyObject *value)
{
	PyObject *res;
3037
	static PyObject *delitem_str, *setitem_str;
3038 3039

	if (value == NULL)
3040
		res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum's avatar
Guido van Rossum committed
3041
				  "(i)", index);
3042
	else
3043
		res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum's avatar
Guido van Rossum committed
3044
				  "(iO)", index, value);
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054
	if (res == NULL)
		return -1;
	Py_DECREF(res);
	return 0;
}

static int
slot_sq_ass_slice(PyObject *self, int i, int j, PyObject *value)
{
	PyObject *res;
3055
	static PyObject *delslice_str, *setslice_str;
3056 3057

	if (value == NULL)
3058
		res = call_method(self, "__delslice__", &delslice_str,
Guido van Rossum's avatar
Guido van Rossum committed
3059
				  "(ii)", i, j);
3060
	else
3061
		res = call_method(self, "__setslice__", &setslice_str,
Guido van Rossum's avatar
Guido van Rossum committed
3062
				  "(iiO)", i, j, value);
3063 3064 3065 3066 3067 3068 3069 3070 3071
	if (res == NULL)
		return -1;
	Py_DECREF(res);
	return 0;
}

static int
slot_sq_contains(PyObject *self, PyObject *value)
{
3072
	PyObject *func, *res, *args;
3073
	static PyObject *contains_str;
3074

3075
	func = lookup_maybe(self, "__contains__", &contains_str);
3076 3077 3078 3079 3080 3081

	if (func != NULL) {
		args = Py_BuildValue("(O)", value);
		if (args == NULL)
			res = NULL;
		else {
Guido van Rossum's avatar
Guido van Rossum committed
3082
			res = PyObject_Call(func, args, NULL);
3083 3084 3085 3086 3087 3088 3089
			Py_DECREF(args);
		}
		Py_DECREF(func);
		if (res == NULL)
			return -1;
		return PyObject_IsTrue(res);
	}
3090 3091
	else if (PyErr_Occurred())
		return -1;
3092
	else {
3093 3094
		return _PySequence_IterSearch(self, value,
					      PY_ITERSEARCH_CONTAINS);
3095
	}
3096 3097
}

3098 3099
SLOT1(slot_sq_inplace_concat, "__iadd__", PyObject *, "O")
SLOT1(slot_sq_inplace_repeat, "__imul__", int, "i")
3100 3101 3102

#define slot_mp_length slot_sq_length

3103
SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
3104 3105 3106 3107 3108

static int
slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
{
	PyObject *res;
3109
	static PyObject *delitem_str, *setitem_str;
3110 3111

	if (value == NULL)
3112
		res = call_method(self, "__delitem__", &delitem_str,
Guido van Rossum's avatar
Guido van Rossum committed
3113
				  "(O)", key);
3114
	else
3115
		res = call_method(self, "__setitem__", &setitem_str,
Guido van Rossum's avatar
Guido van Rossum committed
3116
				 "(OO)", key, value);
3117 3118 3119 3120 3121 3122
	if (res == NULL)
		return -1;
	Py_DECREF(res);
	return 0;
}

3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__")
SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__")
SLOT1BIN(slot_nb_divide, nb_divide, "__div__", "__rdiv__")
SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__")
SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")

staticforward PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);

SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
	     nb_power, "__pow__", "__rpow__")

static PyObject *
slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
{
3138 3139
	static PyObject *pow_str;

3140 3141
	if (modulus == Py_None)
		return slot_nb_power_binary(self, other);
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
	/* Three-arg power doesn't use __rpow__.  But ternary_op
	   can call this when the second argument's type uses
	   slot_nb_power, so check before calling self.__pow__. */
	if (self->ob_type->tp_as_number != NULL &&
	    self->ob_type->tp_as_number->nb_power == slot_nb_power) {
		return call_method(self, "__pow__", &pow_str,
				   "(OO)", other, modulus);
	}
	Py_INCREF(Py_NotImplemented);
	return Py_NotImplemented;
3152 3153 3154 3155 3156
}

SLOT0(slot_nb_negative, "__neg__")
SLOT0(slot_nb_positive, "__pos__")
SLOT0(slot_nb_absolute, "__abs__")
3157 3158 3159 3160

static int
slot_nb_nonzero(PyObject *self)
{
3161
	PyObject *func, *res;
3162
	static PyObject *nonzero_str, *len_str;
3163

3164
	func = lookup_maybe(self, "__nonzero__", &nonzero_str);
3165
	if (func == NULL) {
3166
		if (PyErr_Occurred())
3167
			return -1;
3168 3169 3170 3171 3172 3173 3174
		func = lookup_maybe(self, "__len__", &len_str);
		if (func == NULL) {
			if (PyErr_Occurred())
				return -1;
			else
				return 1;
		}
3175
	}
3176 3177 3178 3179 3180
	res = PyObject_CallObject(func, NULL);
	Py_DECREF(func);
	if (res == NULL)
		return -1;
	return PyObject_IsTrue(res);
3181 3182
}

3183 3184 3185 3186 3187 3188
SLOT0(slot_nb_invert, "__invert__")
SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__")
SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__")
SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__")
SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__")
SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205

static int
slot_nb_coerce(PyObject **a, PyObject **b)
{
	static PyObject *coerce_str;
	PyObject *self = *a, *other = *b;

	if (self->ob_type->tp_as_number != NULL &&
	    self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
		PyObject *r;
		r = call_maybe(
			self, "__coerce__", &coerce_str, "(O)", other);
		if (r == NULL)
			return -1;
		if (r == Py_NotImplemented) {
			Py_DECREF(r);
		}
3206 3207 3208
		else {
			if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
				PyErr_SetString(PyExc_TypeError,
3209
					"__coerce__ didn't return a 2-tuple");
3210 3211 3212 3213 3214 3215 3216
				Py_DECREF(r);
				return -1;
			}
			*a = PyTuple_GET_ITEM(r, 0);
			Py_INCREF(*a);
			*b = PyTuple_GET_ITEM(r, 1);
			Py_INCREF(*b);
3217
			Py_DECREF(r);
3218
			return 0;
3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247
		}
	}
	if (other->ob_type->tp_as_number != NULL &&
	    other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
		PyObject *r;
		r = call_maybe(
			other, "__coerce__", &coerce_str, "(O)", self);
		if (r == NULL)
			return -1;
		if (r == Py_NotImplemented) {
			Py_DECREF(r);
			return 1;
		}
		if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
			PyErr_SetString(PyExc_TypeError,
					"__coerce__ didn't return a 2-tuple");
			Py_DECREF(r);
			return -1;
		}
		*a = PyTuple_GET_ITEM(r, 1);
		Py_INCREF(*a);
		*b = PyTuple_GET_ITEM(r, 0);
		Py_INCREF(*b);
		Py_DECREF(r);
		return 0;
	}
	return 1;
}

3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
SLOT0(slot_nb_int, "__int__")
SLOT0(slot_nb_long, "__long__")
SLOT0(slot_nb_float, "__float__")
SLOT0(slot_nb_oct, "__oct__")
SLOT0(slot_nb_hex, "__hex__")
SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *, "O")
SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
SLOT2(slot_nb_inplace_power, "__ipow__", PyObject *, PyObject *, "OO")
SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
	 "__floordiv__", "__rfloordiv__")
SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
3269

3270 3271 3272 3273
static int
half_compare(PyObject *self, PyObject *other)
{
	PyObject *func, *args, *res;
3274
	static PyObject *cmp_str;
3275 3276
	int c;

3277
	func = lookup_method(self, "__cmp__", &cmp_str);
3278 3279 3280 3281 3282 3283 3284 3285
	if (func == NULL) {
		PyErr_Clear();
	}
	else {
		args = Py_BuildValue("(O)", other);
		if (args == NULL)
			res = NULL;
		else {
Guido van Rossum's avatar
Guido van Rossum committed
3286
			res = PyObject_Call(func, args, NULL);
3287 3288
			Py_DECREF(args);
		}
3289
		Py_DECREF(func);
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
		if (res != Py_NotImplemented) {
			if (res == NULL)
				return -2;
			c = PyInt_AsLong(res);
			Py_DECREF(res);
			if (c == -1 && PyErr_Occurred())
				return -2;
			return (c < 0) ? -1 : (c > 0) ? 1 : 0;
		}
		Py_DECREF(res);
	}
	return 2;
}

3304 3305 3306
/* This slot is published for the benefit of try_3way_compare in object.c */
int
_PyObject_SlotCompare(PyObject *self, PyObject *other)
3307
{
3308
	int c;
3309

3310
	if (self->ob_type->tp_compare == _PyObject_SlotCompare) {
3311 3312 3313 3314
		c = half_compare(self, other);
		if (c <= 1)
			return c;
	}
3315
	if (other->ob_type->tp_compare == _PyObject_SlotCompare) {
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
		c = half_compare(other, self);
		if (c < -1)
			return -2;
		if (c <= 1)
			return -c;
	}
	return (void *)self < (void *)other ? -1 :
		(void *)self > (void *)other ? 1 : 0;
}

static PyObject *
slot_tp_repr(PyObject *self)
{
	PyObject *func, *res;
3330
	static PyObject *repr_str;
3331

3332
	func = lookup_method(self, "__repr__", &repr_str);
3333 3334 3335 3336 3337
	if (func != NULL) {
		res = PyEval_CallObject(func, NULL);
		Py_DECREF(func);
		return res;
	}
3338 3339 3340
	PyErr_Clear();
	return PyString_FromFormat("<%s object at %p>",
				   self->ob_type->tp_name, self);
3341 3342
}

3343 3344 3345 3346
static PyObject *
slot_tp_str(PyObject *self)
{
	PyObject *func, *res;
3347
	static PyObject *str_str;
3348

3349
	func = lookup_method(self, "__str__", &str_str);
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
	if (func != NULL) {
		res = PyEval_CallObject(func, NULL);
		Py_DECREF(func);
		return res;
	}
	else {
		PyErr_Clear();
		return slot_tp_repr(self);
	}
}
3360 3361 3362 3363

static long
slot_tp_hash(PyObject *self)
{
3364
	PyObject *func, *res;
3365 3366
	static PyObject *hash_str, *eq_str, *cmp_str;

3367 3368
	long h;

3369
	func = lookup_method(self, "__hash__", &hash_str);
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379

	if (func != NULL) {
		res = PyEval_CallObject(func, NULL);
		Py_DECREF(func);
		if (res == NULL)
			return -1;
		h = PyInt_AsLong(res);
	}
	else {
		PyErr_Clear();
3380
		func = lookup_method(self, "__eq__", &eq_str);
3381 3382
		if (func == NULL) {
			PyErr_Clear();
3383
			func = lookup_method(self, "__cmp__", &cmp_str);
3384 3385 3386 3387 3388 3389 3390 3391 3392
		}
		if (func != NULL) {
			Py_DECREF(func);
			PyErr_SetString(PyExc_TypeError, "unhashable type");
			return -1;
		}
		PyErr_Clear();
		h = _Py_HashPointer((void *)self);
	}
3393 3394 3395 3396 3397 3398 3399 3400
	if (h == -1 && !PyErr_Occurred())
		h = -2;
	return h;
}

static PyObject *
slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
{
3401 3402
	static PyObject *call_str;
	PyObject *meth = lookup_method(self, "__call__", &call_str);
3403 3404 3405 3406 3407 3408 3409 3410 3411
	PyObject *res;

	if (meth == NULL)
		return NULL;
	res = PyObject_Call(meth, args, kwds);
	Py_DECREF(meth);
	return res;
}

3412 3413 3414 3415 3416 3417 3418
/* There are two slot dispatch functions for tp_getattro.

   - slot_tp_getattro() is used when __getattribute__ is overridden
     but no __getattr__ hook is present;

   - slot_tp_getattr_hook() is used when a __getattr__ hook is present.

3419 3420 3421
   The code in update_one_slot() always installs slot_tp_getattr_hook(); this
   detects the absence of __getattr__ and then installs the simpler slot if
   necessary. */
3422

3423 3424 3425
static PyObject *
slot_tp_getattro(PyObject *self, PyObject *name)
{
3426 3427 3428
	static PyObject *getattribute_str = NULL;
	return call_method(self, "__getattribute__", &getattribute_str,
			   "(O)", name);
3429 3430
}

3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
static PyObject *
slot_tp_getattr_hook(PyObject *self, PyObject *name)
{
	PyTypeObject *tp = self->ob_type;
	PyObject *getattr, *getattribute, *res;
	static PyObject *getattribute_str = NULL;
	static PyObject *getattr_str = NULL;

	if (getattr_str == NULL) {
		getattr_str = PyString_InternFromString("__getattr__");
		if (getattr_str == NULL)
			return NULL;
	}
	if (getattribute_str == NULL) {
		getattribute_str =
			PyString_InternFromString("__getattribute__");
		if (getattribute_str == NULL)
			return NULL;
	}
	getattr = _PyType_Lookup(tp, getattr_str);
3451
	if (getattr == NULL) {
3452 3453 3454 3455
		/* No __getattr__ hook: use a simpler dispatcher */
		tp->tp_getattro = slot_tp_getattro;
		return slot_tp_getattro(self, name);
	}
3456
	getattribute = _PyType_Lookup(tp, getattribute_str);
3457 3458 3459 3460
	if (getattribute == NULL ||
	    (getattribute->ob_type == &PyWrapperDescr_Type &&
	     ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
	     (void *)PyObject_GenericGetAttr))
3461 3462 3463
		res = PyObject_GenericGetAttr(self, name);
	else
		res = PyObject_CallFunction(getattribute, "OO", self, name);
3464
	if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
3465 3466 3467 3468 3469 3470
		PyErr_Clear();
		res = PyObject_CallFunction(getattr, "OO", self, name);
	}
	return res;
}

3471 3472 3473 3474
static int
slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
{
	PyObject *res;
3475
	static PyObject *delattr_str, *setattr_str;
3476 3477

	if (value == NULL)
3478
		res = call_method(self, "__delattr__", &delattr_str,
Guido van Rossum's avatar
Guido van Rossum committed
3479
				  "(O)", name);
3480
	else
3481
		res = call_method(self, "__setattr__", &setattr_str,
Guido van Rossum's avatar
Guido van Rossum committed
3482
				  "(OO)", name, value);
3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
	if (res == NULL)
		return -1;
	Py_DECREF(res);
	return 0;
}

/* Map rich comparison operators to their __xx__ namesakes */
static char *name_op[] = {
	"__lt__",
	"__le__",
	"__eq__",
	"__ne__",
	"__gt__",
	"__ge__",
};

3499 3500 3501 3502
static PyObject *
half_richcompare(PyObject *self, PyObject *other, int op)
{
	PyObject *func, *args, *res;
3503
	static PyObject *op_str[6];
3504

3505
	func = lookup_method(self, name_op[op], &op_str[op]);
3506 3507 3508 3509 3510 3511 3512 3513 3514
	if (func == NULL) {
		PyErr_Clear();
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	args = Py_BuildValue("(O)", other);
	if (args == NULL)
		res = NULL;
	else {
Guido van Rossum's avatar
Guido van Rossum committed
3515
		res = PyObject_Call(func, args, NULL);
3516 3517 3518 3519 3520 3521 3522 3523 3524
		Py_DECREF(args);
	}
	Py_DECREF(func);
	return res;
}

/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};

3525 3526 3527 3528 3529
static PyObject *
slot_tp_richcompare(PyObject *self, PyObject *other, int op)
{
	PyObject *res;

3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
	if (self->ob_type->tp_richcompare == slot_tp_richcompare) {
		res = half_richcompare(self, other, op);
		if (res != Py_NotImplemented)
			return res;
		Py_DECREF(res);
	}
	if (other->ob_type->tp_richcompare == slot_tp_richcompare) {
		res = half_richcompare(other, self, swapped_op[op]);
		if (res != Py_NotImplemented) {
			return res;
		}
		Py_DECREF(res);
	}
	Py_INCREF(Py_NotImplemented);
	return Py_NotImplemented;
3545 3546
}

3547 3548 3549 3550
static PyObject *
slot_tp_iter(PyObject *self)
{
	PyObject *func, *res;
3551
	static PyObject *iter_str, *getitem_str;
3552

3553
	func = lookup_method(self, "__iter__", &iter_str);
3554 3555 3556 3557 3558 3559
	if (func != NULL) {
		 res = PyObject_CallObject(func, NULL);
		 Py_DECREF(func);
		 return res;
	}
	PyErr_Clear();
3560
	func = lookup_method(self, "__getitem__", &getitem_str);
3561
	if (func == NULL) {
3562 3563
		PyErr_SetString(PyExc_TypeError,
				"iteration over non-sequence");
3564 3565 3566 3567 3568
		return NULL;
	}
	Py_DECREF(func);
	return PySeqIter_New(self);
}
3569 3570 3571 3572

static PyObject *
slot_tp_iternext(PyObject *self)
{
3573
	static PyObject *next_str;
Guido van Rossum's avatar
Guido van Rossum committed
3574
	return call_method(self, "next", &next_str, "()");
3575 3576
}

3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
static PyObject *
slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
	PyTypeObject *tp = self->ob_type;
	PyObject *get;
	static PyObject *get_str = NULL;

	if (get_str == NULL) {
		get_str = PyString_InternFromString("__get__");
		if (get_str == NULL)
			return NULL;
	}
	get = _PyType_Lookup(tp, get_str);
	if (get == NULL) {
		/* Avoid further slowdowns */
		if (tp->tp_descr_get == slot_tp_descr_get)
			tp->tp_descr_get = NULL;
		Py_INCREF(self);
		return self;
	}
3597 3598 3599 3600
	if (obj == NULL)
		obj = Py_None;
	if (type == NULL)
		type = Py_None;
3601 3602
	return PyObject_CallFunction(get, "OOO", self, obj, type);
}
3603 3604 3605 3606

static int
slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
{
3607
	PyObject *res;
3608
	static PyObject *del_str, *set_str;
3609 3610

	if (value == NULL)
3611
		res = call_method(self, "__delete__", &del_str,
Guido van Rossum's avatar
Guido van Rossum committed
3612
				  "(O)", target);
3613
	else
3614
		res = call_method(self, "__set__", &set_str,
Guido van Rossum's avatar
Guido van Rossum committed
3615
				  "(OO)", target, value);
3616 3617 3618 3619 3620 3621 3622 3623 3624
	if (res == NULL)
		return -1;
	Py_DECREF(res);
	return 0;
}

static int
slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
{
3625 3626
	static PyObject *init_str;
	PyObject *meth = lookup_method(self, "__init__", &init_str);
3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660
	PyObject *res;

	if (meth == NULL)
		return -1;
	res = PyObject_Call(meth, args, kwds);
	Py_DECREF(meth);
	if (res == NULL)
		return -1;
	Py_DECREF(res);
	return 0;
}

static PyObject *
slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *func = PyObject_GetAttrString((PyObject *)type, "__new__");
	PyObject *newargs, *x;
	int i, n;

	if (func == NULL)
		return NULL;
	assert(PyTuple_Check(args));
	n = PyTuple_GET_SIZE(args);
	newargs = PyTuple_New(n+1);
	if (newargs == NULL)
		return NULL;
	Py_INCREF(type);
	PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
	for (i = 0; i < n; i++) {
		x = PyTuple_GET_ITEM(args, i);
		Py_INCREF(x);
		PyTuple_SET_ITEM(newargs, i+1, x);
	}
	x = PyObject_Call(func, newargs, kwds);
3661
	Py_DECREF(newargs);
3662 3663 3664 3665
	Py_DECREF(func);
	return x;
}

Guido van Rossum's avatar
Guido van Rossum committed
3666

3667 3668 3669 3670 3671
/* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper
   functions.  The offsets here are relative to the 'etype' structure, which
   incorporates the additional structures used for numbers, sequences and
   mappings.  Note that multiple names may map to the same slot (e.g. __eq__,
   __ne__ etc. all map to tp_richcompare) and one name may map to multiple
3672 3673 3674
   slots (e.g. __str__ affects tp_str as well as tp_repr). The table is
   terminated with an all-zero entry.  (This table is further initialized and
   sorted in init_slotdefs() below.) */
3675

3676
typedef struct wrapperbase slotdef;
3677 3678

#undef TPSLOT
3679
#undef FLSLOT
3680 3681 3682 3683
#undef ETSLOT
#undef SQSLOT
#undef MPSLOT
#undef NBSLOT
3684 3685
#undef UNSLOT
#undef IBSLOT
3686 3687 3688
#undef BINSLOT
#undef RBINSLOT

3689 3690
#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
3691 3692 3693
#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
	{NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
	 DOC, FLAGS}
3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
	{NAME, offsetof(etype, SLOT), (void *)(FUNCTION), WRAPPER, DOC}
#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
	ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
	ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
	       "x." NAME "() <==> " DOC)
#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
	ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
	       "x." NAME "(y) <==> x" DOC "y")
#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
	       "x." NAME "(y) <==> x" DOC "y")
#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
	ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
	       "x." NAME "(y) <==> y" DOC "x")
3714 3715

static slotdef slotdefs[] = {
3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
	SQSLOT("__len__", sq_length, slot_sq_length, wrap_inquiry,
	       "x.__len__() <==> len(x)"),
	SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
	       "x.__add__(y) <==> x+y"),
	SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
	       "x.__mul__(n) <==> x*n"),
	SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
	       "x.__rmul__(n) <==> n*x"),
	SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
	       "x.__getitem__(y) <==> x[y]"),
	SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_intintargfunc,
	       "x.__getslice__(i, j) <==> x[i:j]"),
	SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
	       "x.__setitem__(i, y) <==> x[i]=y"),
	SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
	       "x.__delitem__(y) <==> del x[y]"),
3732
	SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
3733 3734 3735 3736 3737 3738
	       wrap_intintobjargproc,
	       "x.__setslice__(i, j, y) <==> x[i:j]=y"),
	SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
	       "x.__delslice__(i, j) <==> del x[i:j]"),
	SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
	       "x.__contains__(y) <==> y in x"),
3739
	SQSLOT("__iadd__", sq_inplace_concat, slot_sq_inplace_concat,
3740
	       wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
3741
	SQSLOT("__imul__", sq_inplace_repeat, slot_sq_inplace_repeat,
3742
	       wrap_intargfunc, "x.__imul__(y) <==> x*=y"),
3743

3744 3745
	MPSLOT("__len__", mp_length, slot_mp_length, wrap_inquiry,
	       "x.__len__() <==> len(x)"),
3746
	MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
3747 3748
	       wrap_binaryfunc,
	       "x.__getitem__(y) <==> x[y]"),
3749
	MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
3750 3751
	       wrap_objobjargproc,
	       "x.__setitem__(i, y) <==> x[i]=y"),
3752
	MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787
	       wrap_delitem,
	       "x.__delitem__(y) <==> del x[y]"),

	BINSLOT("__add__", nb_add, slot_nb_add,
		"+"),
	RBINSLOT("__radd__", nb_add, slot_nb_add,
		 "+"),
	BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
		"-"),
	RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
		 "-"),
	BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
		"*"),
	RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
		 "*"),
	BINSLOT("__div__", nb_divide, slot_nb_divide,
		"/"),
	RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
		 "/"),
	BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
		"%"),
	RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
		 "%"),
	BINSLOT("__divmod__", nb_divmod, slot_nb_divmod,
		"divmod(x, y)"),
	RBINSLOT("__rdivmod__", nb_divmod, slot_nb_divmod,
		 "divmod(y, x)"),
	NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
	       "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
	NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
	       "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
	UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
	UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
	UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
	       "abs(x)"),
Guido van Rossum's avatar
Guido van Rossum committed
3788
	UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquiry,
3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845
	       "x != 0"),
	UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
	BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
	RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
	BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
	RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
	BINSLOT("__and__", nb_and, slot_nb_and, "&"),
	RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
	BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
	RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
	BINSLOT("__or__", nb_or, slot_nb_or, "|"),
	RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
	NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
	       "x.__coerce__(y) <==> coerce(x, y)"),
	UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
	       "int(x)"),
	UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
	       "long(x)"),
	UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
	       "float(x)"),
	UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
	       "oct(x)"),
	UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
	       "hex(x)"),
	IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
	       wrap_binaryfunc, "+"),
	IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
	       wrap_binaryfunc, "-"),
	IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
	       wrap_binaryfunc, "*"),
	IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
	       wrap_binaryfunc, "/"),
	IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
	       wrap_binaryfunc, "%"),
	IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
	       wrap_ternaryfunc, "**"),
	IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
	       wrap_binaryfunc, "<<"),
	IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
	       wrap_binaryfunc, ">>"),
	IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
	       wrap_binaryfunc, "&"),
	IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
	       wrap_binaryfunc, "^"),
	IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
	       wrap_binaryfunc, "|"),
	BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
	RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
	BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
	RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
	IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
	       slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
	IBSLOT("__itruediv__", nb_inplace_true_divide,
	       slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),

	TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
	       "x.__str__() <==> str(x)"),
3846
	TPSLOT("__str__", tp_print, NULL, NULL, ""),
3847 3848
	TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
	       "x.__repr__() <==> repr(x)"),
3849
	TPSLOT("__repr__", tp_print, NULL, NULL, ""),
3850 3851 3852 3853
	TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
	       "x.__cmp__(y) <==> cmp(x,y)"),
	TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
	       "x.__hash__() <==> hash(x)"),
3854 3855
	FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
	       "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
3856
	TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
	       wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
	TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
	TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
	TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
	TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
	       "x.__setattr__('name', value) <==> x.name = value"),
	TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
	TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
	       "x.__delattr__('name') <==> del x.name"),
	TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
	TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
	       "x.__lt__(y) <==> x<y"),
	TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
	       "x.__le__(y) <==> x<=y"),
	TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
	       "x.__eq__(y) <==> x==y"),
	TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
	       "x.__ne__(y) <==> x!=y"),
	TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
	       "x.__gt__(y) <==> x>y"),
	TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
	       "x.__ge__(y) <==> x>=y"),
	TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
	       "x.__iter__() <==> iter(x)"),
	TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
	       "x.next() -> the next value, or raise StopIteration"),
	TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
	       "descr.__get__(obj[, type]) -> value"),
	TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
	       "descr.__set__(obj, value)"),
3887
	FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
3888
	       "x.__init__(...) initializes x; "
3889 3890 3891
	       "see x.__class__.__doc__ for signature",
	       PyWrapperFlag_KEYWORDS),
	TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
3892 3893 3894
	{NULL}
};

3895 3896 3897 3898 3899
/* Given a type pointer and an offset gotten from a slotdef entry, return a
   pointer to the actual slot.  This is not quite the same as simply adding
   the offset to the type pointer, since it takes care to indirect through the
   proper indirection pointer (as_buffer, etc.); it returns NULL if the
   indirection pointer is NULL. */
3900 3901 3902 3903 3904
static void **
slotptr(PyTypeObject *type, int offset)
{
	char *ptr;

3905
	/* Note: this depends on the order of the members of etype! */
3906 3907
	assert(offset >= 0);
	assert(offset < offsetof(etype, as_buffer));
3908
	if (offset >= offsetof(etype, as_sequence)) {
3909 3910 3911
		ptr = (void *)type->tp_as_sequence;
		offset -= offsetof(etype, as_sequence);
	}
3912 3913 3914 3915
	else if (offset >= offsetof(etype, as_mapping)) {
		ptr = (void *)type->tp_as_mapping;
		offset -= offsetof(etype, as_mapping);
	}
3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
	else if (offset >= offsetof(etype, as_number)) {
		ptr = (void *)type->tp_as_number;
		offset -= offsetof(etype, as_number);
	}
	else {
		ptr = (void *)type;
	}
	if (ptr != NULL)
		ptr += offset;
	return (void **)ptr;
}

3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024
/* Length of array of slotdef pointers used to store slots with the
   same __name__.  There should be at most MAX_EQUIV-1 slotdef entries with
   the same __name__, for any __name__. Since that's a static property, it is
   appropriate to declare fixed-size arrays for this. */
#define MAX_EQUIV 10

/* Return a slot pointer for a given name, but ONLY if the attribute has
   exactly one slot function.  The name must be an interned string. */
static void **
resolve_slotdups(PyTypeObject *type, PyObject *name)
{
	/* XXX Maybe this could be optimized more -- but is it worth it? */

	/* pname and ptrs act as a little cache */
	static PyObject *pname;
	static slotdef *ptrs[MAX_EQUIV];
	slotdef *p, **pp;
	void **res, **ptr;

	if (pname != name) {
		/* Collect all slotdefs that match name into ptrs. */
		pname = name;
		pp = ptrs;
		for (p = slotdefs; p->name_strobj; p++) {
			if (p->name_strobj == name)
				*pp++ = p;
		}
		*pp = NULL;
	}

	/* Look in all matching slots of the type; if exactly one of these has
	   a filled-in slot, return its value.  Otherwise return NULL. */
	res = NULL;
	for (pp = ptrs; *pp; pp++) {
		ptr = slotptr(type, (*pp)->offset);
		if (ptr == NULL || *ptr == NULL)
			continue;
		if (res != NULL)
			return NULL;
		res = ptr;
	}
	return res;
}

/* Common code for update_these_slots() and fixup_slot_dispatchers().  This
   does some incredibly complex thinking and then sticks something into the
   slot.  (It sees if the adjacent slotdefs for the same slot have conflicting
   interests, and then stores a generic wrapper or a specific function into
   the slot.)  Return a pointer to the next slotdef with a different offset,
   because that's convenient  for fixup_slot_dispatchers(). */
static slotdef *
update_one_slot(PyTypeObject *type, slotdef *p)
{
	PyObject *descr;
	PyWrapperDescrObject *d;
	void *generic = NULL, *specific = NULL;
	int use_generic = 0;
	int offset = p->offset;
	void **ptr = slotptr(type, offset);

	if (ptr == NULL) {
		do {
			++p;
		} while (p->offset == offset);
		return p;
	}
	do {
		descr = _PyType_Lookup(type, p->name_strobj);
		if (descr == NULL)
			continue;
		if (descr->ob_type == &PyWrapperDescr_Type) {
			void **tptr = resolve_slotdups(type, p->name_strobj);
			if (tptr == NULL || tptr == ptr)
				generic = p->function;
			d = (PyWrapperDescrObject *)descr;
			if (d->d_base->wrapper == p->wrapper &&
			    PyType_IsSubtype(type, d->d_type))
			{
				if (specific == NULL ||
				    specific == d->d_wrapped)
					specific = d->d_wrapped;
				else
					use_generic = 1;
			}
		}
		else {
			use_generic = 1;
			generic = p->function;
		}
	} while ((++p)->offset == offset);
	if (specific && !use_generic)
		*ptr = specific;
	else
		*ptr = generic;
	return p;
}

4025 4026
staticforward int recurse_down_subclasses(PyTypeObject *type,
					  slotdef **pp, PyObject *name);
4027

4028 4029
/* In the type, update the slots whose slotdefs are gathered in the pp0 array,
   and then do the same for all this type's subtypes. */
4030
static int
4031
update_these_slots(PyTypeObject *type, slotdef **pp0, PyObject *name)
4032
{
4033
	slotdef **pp;
4034

4035 4036
	for (pp = pp0; *pp; pp++)
		update_one_slot(type, *pp);
4037
	return recurse_down_subclasses(type, pp0, name);
4038 4039
}

4040 4041
/* Update the slots whose slotdefs are gathered in the pp array in all (direct
   or indirect) subclasses of type. */
4042
static int
4043
recurse_down_subclasses(PyTypeObject *type, slotdef **pp, PyObject *name)
4044 4045
{
	PyTypeObject *subclass;
4046
	PyObject *ref, *subclasses, *dict;
4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057
	int i, n;

	subclasses = type->tp_subclasses;
	if (subclasses == NULL)
		return 0;
	assert(PyList_Check(subclasses));
	n = PyList_GET_SIZE(subclasses);
	for (i = 0; i < n; i++) {
		ref = PyList_GET_ITEM(subclasses, i);
		assert(PyWeakref_CheckRef(ref));
		subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
4058 4059
		assert(subclass != NULL);
		if ((PyObject *)subclass == Py_None)
4060 4061
			continue;
		assert(PyType_Check(subclass));
4062 4063 4064 4065 4066 4067
		/* Avoid recursing down into unaffected classes */
		dict = subclass->tp_dict;
		if (dict != NULL && PyDict_Check(dict) &&
		    PyDict_GetItem(dict, name) != NULL)
			continue;
		if (update_these_slots(subclass, pp, name) < 0)
4068 4069 4070 4071 4072
			return -1;
	}
	return 0;
}

4073 4074
/* Comparison function for qsort() to compare slotdefs by their offset, and
   for equal offset by their address (to force a stable sort). */
4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085
static int
slotdef_cmp(const void *aa, const void *bb)
{
	const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
	int c = a->offset - b->offset;
	if (c != 0)
		return c;
	else
		return a - b;
}

4086 4087
/* Initialize the slotdefs table by adding interned string objects for the
   names and sorting the entries. */
4088
static void
4089
init_slotdefs(void)
4090 4091 4092 4093 4094 4095 4096 4097 4098
{
	slotdef *p;
	static int initialized = 0;

	if (initialized)
		return;
	for (p = slotdefs; p->name; p++) {
		p->name_strobj = PyString_InternFromString(p->name);
		if (!p->name_strobj)
4099
			Py_FatalError("Out of memory interning slotdef names");
4100
	}
4101 4102
	qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
	      slotdef_cmp);
4103 4104 4105
	initialized = 1;
}

4106
/* Update the slots after assignment to a class (type) attribute. */
4107 4108 4109
static int
update_slot(PyTypeObject *type, PyObject *name)
{
4110
	slotdef *ptrs[MAX_EQUIV];
4111 4112
	slotdef *p;
	slotdef **pp;
4113
	int offset;
4114

4115 4116 4117 4118 4119 4120 4121 4122
	init_slotdefs();
	pp = ptrs;
	for (p = slotdefs; p->name; p++) {
		/* XXX assume name is interned! */
		if (p->name_strobj == name)
			*pp++ = p;
	}
	*pp = NULL;
4123 4124
	for (pp = ptrs; *pp; pp++) {
		p = *pp;
4125 4126
		offset = p->offset;
		while (p > slotdefs && (p-1)->offset == offset)
4127
			--p;
4128
		*pp = p;
4129
	}
4130 4131
	if (ptrs[0] == NULL)
		return 0; /* Not an attribute that affects any slots */
4132
	return update_these_slots(type, ptrs, name);
4133 4134
}

4135 4136 4137
/* Store the proper functions in the slot dispatches at class (type)
   definition time, based upon which operations the class overrides in its
   dict. */
4138 4139 4140 4141 4142
static void
fixup_slot_dispatchers(PyTypeObject *type)
{
	slotdef *p;

4143
	init_slotdefs();
4144 4145
	for (p = slotdefs; p->name; )
		p = update_one_slot(type, p);
4146
}
4147

4148 4149
/* This function is called by PyType_Ready() to populate the type's
   dictionary with method descriptors for function slots.  For each
4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
   function slot (like tp_repr) that's defined in the type, one or more
   corresponding descriptors are added in the type's tp_dict dictionary
   under the appropriate name (like __repr__).  Some function slots
   cause more than one descriptor to be added (for example, the nb_add
   slot adds both __add__ and __radd__ descriptors) and some function
   slots compete for the same descriptor (for example both sq_item and
   mp_subscript generate a __getitem__ descriptor).

   In the latter case, the first slotdef entry encoutered wins.  Since
   slotdef entries are sorted by the offset of the slot in the etype
   struct, this gives us some control over disambiguating between
   competing slots: the members of struct etype are listed from most
   general to least general, so the most general slot is preferred.  In
   particular, because as_mapping comes before as_sequence, for a type
   that defines both mp_subscript and sq_item, mp_subscript wins.

   This only adds new descriptors and doesn't overwrite entries in
   tp_dict that were previously defined.  The descriptors contain a
   reference to the C function they must call, so that it's safe if they
   are copied into a subtype's __dict__ and the subtype has a different
   C function in its slot -- calling the method defined by the
   descriptor will call the C function that was used to create it,
   rather than the C function present in the slot when it is called.
   (This is important because a subtype may have a C function in the
   slot that calls the method from the dictionary, and we want to avoid
   infinite recursion here.) */
4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207

static int
add_operators(PyTypeObject *type)
{
	PyObject *dict = type->tp_dict;
	slotdef *p;
	PyObject *descr;
	void **ptr;

	init_slotdefs();
	for (p = slotdefs; p->name; p++) {
		if (p->wrapper == NULL)
			continue;
		ptr = slotptr(type, p->offset);
		if (!ptr || !*ptr)
			continue;
		if (PyDict_GetItem(dict, p->name_strobj))
			continue;
		descr = PyDescr_NewWrapper(type, p, *ptr);
		if (descr == NULL)
			return -1;
		if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
			return -1;
		Py_DECREF(descr);
	}
	if (type->tp_new != NULL) {
		if (add_tp_new_wrapper(type) < 0)
			return -1;
	}
	return 0;
}

4208 4209 4210 4211 4212

/* Cooperative 'super' */

typedef struct {
	PyObject_HEAD
4213
	PyTypeObject *type;
4214 4215 4216
	PyObject *obj;
} superobject;

4217 4218 4219 4220 4221
static PyMemberDef super_members[] = {
	{"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
	 "the class invoking super()"},
	{"__self__",  T_OBJECT, offsetof(superobject, obj), READONLY,
	 "the instance invoking super(); may be None"},
4222 4223 4224
	{0}
};

4225 4226 4227 4228 4229
static void
super_dealloc(PyObject *self)
{
	superobject *su = (superobject *)self;

4230
	_PyObject_GC_UNTRACK(self);
4231 4232 4233 4234 4235
	Py_XDECREF(su->obj);
	Py_XDECREF(su->type);
	self->ob_type->tp_free(self);
}

4236 4237 4238 4239 4240 4241 4242
static PyObject *
super_repr(PyObject *self)
{
	superobject *su = (superobject *)self;

	if (su->obj)
		return PyString_FromFormat(
4243
			"<super: <class '%s'>, <%s object>>",
4244 4245 4246 4247
			su->type ? su->type->tp_name : "NULL",
			su->obj->ob_type->tp_name);
	else
		return PyString_FromFormat(
4248
			"<super: <class '%s'>, NULL>",
4249 4250 4251
			su->type ? su->type->tp_name : "NULL");
}

4252 4253 4254 4255 4256 4257
static PyObject *
super_getattro(PyObject *self, PyObject *name)
{
	superobject *su = (superobject *)self;

	if (su->obj != NULL) {
4258
		PyObject *mro, *res, *tmp, *dict;
4259
		PyTypeObject *starttype;
4260 4261 4262
		descrgetfunc f;
		int i, n;

4263 4264 4265
		starttype = su->obj->ob_type;
		mro = starttype->tp_mro;

4266 4267 4268 4269 4270 4271
		if (mro == NULL)
			n = 0;
		else {
			assert(PyTuple_Check(mro));
			n = PyTuple_GET_SIZE(mro);
		}
4272
		for (i = 0; i < n; i++) {
4273
			if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
4274 4275
				break;
		}
4276
		if (i >= n && PyType_Check(su->obj)) {
4277 4278
			starttype = (PyTypeObject *)(su->obj);
			mro = starttype->tp_mro;
4279 4280 4281 4282 4283 4284
			if (mro == NULL)
				n = 0;
			else {
				assert(PyTuple_Check(mro));
				n = PyTuple_GET_SIZE(mro);
			}
4285 4286 4287 4288 4289 4290
			for (i = 0; i < n; i++) {
				if ((PyObject *)(su->type) ==
				    PyTuple_GET_ITEM(mro, i))
					break;
			}
		}
4291 4292 4293 4294
		i++;
		res = NULL;
		for (; i < n; i++) {
			tmp = PyTuple_GET_ITEM(mro, i);
4295 4296 4297 4298 4299 4300 4301
			if (PyType_Check(tmp))
				dict = ((PyTypeObject *)tmp)->tp_dict;
			else if (PyClass_Check(tmp))
				dict = ((PyClassObject *)tmp)->cl_dict;
			else
				continue;
			res = PyDict_GetItem(dict, name);
4302
			if (res != NULL  && !PyDescr_IsData(res)) {
4303 4304 4305
				Py_INCREF(res);
				f = res->ob_type->tp_descr_get;
				if (f != NULL) {
4306 4307
					tmp = f(res, su->obj,
						(PyObject *)starttype);
4308 4309 4310 4311 4312 4313 4314 4315 4316 4317
					Py_DECREF(res);
					res = tmp;
				}
				return res;
			}
		}
	}
	return PyObject_GenericGetAttr(self, name);
}

4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
static int
supercheck(PyTypeObject *type, PyObject *obj)
{
	if (!PyType_IsSubtype(obj->ob_type, type) &&
	    !(PyType_Check(obj) &&
	      PyType_IsSubtype((PyTypeObject *)obj, type))) {
		PyErr_SetString(PyExc_TypeError,
			"super(type, obj): "
			"obj must be an instance or subtype of type");
		return -1;
	}
	else
		return 0;
}

4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343
static PyObject *
super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
	superobject *su = (superobject *)self;
	superobject *new;

	if (obj == NULL || obj == Py_None || su->obj != NULL) {
		/* Not binding to an object, or already bound */
		Py_INCREF(self);
		return self;
	}
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362
	if (su->ob_type != &PySuper_Type)
		/* If su is an instance of a subclass of super,
		   call its type */
		return PyObject_CallFunction((PyObject *)su->ob_type,
					     "OO", su->type, obj);
	else {
		/* Inline the common case */
		if (supercheck(su->type, obj) < 0)
			return NULL;
		new = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
							 NULL, NULL);
		if (new == NULL)
			return NULL;
		Py_INCREF(su->type);
		Py_INCREF(obj);
		new->type = su->type;
		new->obj = obj;
		return (PyObject *)new;
	}
4363 4364 4365 4366 4367 4368
}

static int
super_init(PyObject *self, PyObject *args, PyObject *kwds)
{
	superobject *su = (superobject *)self;
4369 4370
	PyTypeObject *type;
	PyObject *obj = NULL;
4371 4372 4373 4374 4375

	if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
		return -1;
	if (obj == Py_None)
		obj = NULL;
4376
	if (obj != NULL && supercheck(type, obj) < 0)
4377 4378 4379 4380 4381 4382 4383 4384
		return -1;
	Py_INCREF(type);
	Py_XINCREF(obj);
	su->type = type;
	su->obj = obj;
	return 0;
}

4385
PyDoc_STRVAR(super_doc,
4386 4387
"super(type) -> unbound super object\n"
"super(type, obj) -> bound super object; requires isinstance(obj, type)\n"
4388
"super(type, type2) -> bound super object; requires issubclass(type2, type)\n"
4389 4390 4391
"Typical use to call a cooperative superclass method:\n"
"class C(B):\n"
"    def meth(self, arg):\n"
4392
"        super(C, self).meth(arg)");
4393

4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414
static int
super_traverse(PyObject *self, visitproc visit, void *arg)
{
	superobject *su = (superobject *)self;
	int err;

#define VISIT(SLOT) \
	if (SLOT) { \
		err = visit((PyObject *)(SLOT), arg); \
		if (err) \
			return err; \
	}

	VISIT(su->obj);
	VISIT(su->type);

#undef VISIT

	return 0;
}

4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426
PyTypeObject PySuper_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,					/* ob_size */
	"super",				/* tp_name */
	sizeof(superobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	super_dealloc,		 		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
4427
	super_repr,				/* tp_repr */
4428 4429 4430 4431 4432 4433 4434 4435 4436
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,		       			/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	super_getattro,				/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
4437 4438
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
		Py_TPFLAGS_BASETYPE,		/* tp_flags */
4439
 	super_doc,				/* tp_doc */
4440
 	super_traverse,				/* tp_traverse */
4441 4442 4443 4444 4445 4446
 	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
4447
	super_members,				/* tp_members */
4448 4449 4450 4451 4452 4453 4454 4455 4456
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	super_descr_get,			/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
	super_init,				/* tp_init */
	PyType_GenericAlloc,			/* tp_alloc */
	PyType_GenericNew,			/* tp_new */
4457
	PyObject_GC_Del,        		/* tp_free */
4458
};