PageRenderTime 137ms CodeModel.GetById 27ms app.highlight 96ms RepoModel.GetById 1ms app.codeStats 1ms

/Objects/classobject.c

http://unladen-swallow.googlecode.com/
C | 2689 lines | 2347 code | 215 blank | 127 comment | 730 complexity | 60d08320b03f22639ec127f56863a7cf MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1
   2/* Class object implementation */
   3
   4#include "Python.h"
   5#include "structmember.h"
   6
   7/* Free list for method objects to safe malloc/free overhead
   8 * The im_self element is used to chain the elements.
   9 */
  10static PyMethodObject *free_list;
  11static int numfree = 0;
  12#ifndef PyMethod_MAXFREELIST
  13#define PyMethod_MAXFREELIST 256
  14#endif
  15
  16#define TP_DESCR_GET(t) \
  17    (PyType_HasFeature(t, Py_TPFLAGS_HAVE_CLASS) ? (t)->tp_descr_get : NULL)
  18
  19/* Forward */
  20static PyObject *class_lookup(PyClassObject *, PyObject *,
  21			      PyClassObject **);
  22static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
  23static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
  24
  25static PyObject *getattrstr, *setattrstr, *delattrstr;
  26
  27
  28PyObject *
  29PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
  30     /* bases is NULL or tuple of classobjects! */
  31{
  32	PyClassObject *op, *dummy;
  33	static PyObject *docstr, *modstr, *namestr;
  34	if (docstr == NULL) {
  35		docstr= PyString_InternFromString("__doc__");
  36		if (docstr == NULL)
  37			return NULL;
  38	}
  39	if (modstr == NULL) {
  40		modstr= PyString_InternFromString("__module__");
  41		if (modstr == NULL)
  42			return NULL;
  43	}
  44	if (namestr == NULL) {
  45		namestr= PyString_InternFromString("__name__");
  46		if (namestr == NULL)
  47			return NULL;
  48	}
  49	if (name == NULL || !PyString_Check(name)) {
  50		PyErr_SetString(PyExc_TypeError,
  51				"PyClass_New: name must be a string");
  52		return NULL;
  53	}
  54	if (dict == NULL || !PyDict_Check(dict)) {
  55		PyErr_SetString(PyExc_TypeError,
  56				"PyClass_New: dict must be a dictionary");
  57		return NULL;
  58	}
  59	if (PyDict_GetItem(dict, docstr) == NULL) {
  60		if (PyDict_SetItem(dict, docstr, Py_None) < 0)
  61			return NULL;
  62	}
  63	if (PyDict_GetItem(dict, modstr) == NULL) {
  64		PyObject *globals = PyEval_GetGlobals();
  65		if (globals != NULL) {
  66			PyObject *modname = PyDict_GetItem(globals, namestr);
  67			if (modname != NULL) {
  68				if (PyDict_SetItem(dict, modstr, modname) < 0)
  69					return NULL;
  70			}
  71		}
  72	}
  73	if (bases == NULL) {
  74		bases = PyTuple_New(0);
  75		if (bases == NULL)
  76			return NULL;
  77	}
  78	else {
  79		Py_ssize_t i, n;
  80		PyObject *base;
  81		if (!PyTuple_Check(bases)) {
  82			PyErr_SetString(PyExc_TypeError,
  83					"PyClass_New: bases must be a tuple");
  84			return NULL;
  85		}
  86		n = PyTuple_Size(bases);
  87		for (i = 0; i < n; i++) {
  88			base = PyTuple_GET_ITEM(bases, i);
  89			if (!PyClass_Check(base)) {
  90				if (PyCallable_Check(
  91					(PyObject *) base->ob_type))
  92					return PyObject_CallFunctionObjArgs(
  93						(PyObject *) base->ob_type,
  94						name, bases, dict, NULL);
  95				PyErr_SetString(PyExc_TypeError,
  96					"PyClass_New: base must be a class");
  97				return NULL;
  98			}
  99		}
 100		Py_INCREF(bases);
 101	}
 102
 103	if (getattrstr == NULL) {
 104		getattrstr = PyString_InternFromString("__getattr__");
 105		if (getattrstr == NULL)
 106			goto alloc_error;
 107		setattrstr = PyString_InternFromString("__setattr__");
 108		if (setattrstr == NULL)
 109			goto alloc_error;
 110		delattrstr = PyString_InternFromString("__delattr__");
 111		if (delattrstr == NULL)
 112			goto alloc_error;
 113	}
 114
 115	op = PyObject_GC_New(PyClassObject, &PyClass_Type);
 116	if (op == NULL) {
 117alloc_error:
 118		Py_DECREF(bases);
 119		return NULL;
 120	}
 121	op->cl_bases = bases;
 122	Py_INCREF(dict);
 123	op->cl_dict = dict;
 124	Py_XINCREF(name);
 125	op->cl_name = name;
 126
 127	op->cl_getattr = class_lookup(op, getattrstr, &dummy);
 128	op->cl_setattr = class_lookup(op, setattrstr, &dummy);
 129	op->cl_delattr = class_lookup(op, delattrstr, &dummy);
 130	Py_XINCREF(op->cl_getattr);
 131	Py_XINCREF(op->cl_setattr);
 132	Py_XINCREF(op->cl_delattr);
 133	_PyObject_GC_TRACK(op);
 134	return (PyObject *) op;
 135}
 136
 137PyObject *
 138PyMethod_Function(PyObject *im)
 139{
 140	if (!PyMethod_Check(im)) {
 141		PyErr_BadInternalCall();
 142		return NULL;
 143	}
 144	return ((PyMethodObject *)im)->im_func;
 145}
 146
 147PyObject *
 148PyMethod_Self(PyObject *im)
 149{
 150	if (!PyMethod_Check(im)) {
 151		PyErr_BadInternalCall();
 152		return NULL;
 153	}
 154	return ((PyMethodObject *)im)->im_self;
 155}
 156
 157PyObject *
 158PyMethod_Class(PyObject *im)
 159{
 160	if (!PyMethod_Check(im)) {
 161		PyErr_BadInternalCall();
 162		return NULL;
 163	}
 164	return ((PyMethodObject *)im)->im_class;
 165}
 166
 167PyDoc_STRVAR(class_doc,
 168"classobj(name, bases, dict)\n\
 169\n\
 170Create a class object.  The name must be a string; the second argument\n\
 171a tuple of classes, and the third a dictionary.");
 172
 173static PyObject *
 174class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 175{
 176	PyObject *name, *bases, *dict;
 177	static char *kwlist[] = {"name", "bases", "dict", 0};
 178
 179	if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
 180					 &name, &bases, &dict))
 181		return NULL;
 182	return PyClass_New(bases, dict, name);
 183}
 184
 185/* Class methods */
 186
 187static void
 188class_dealloc(PyClassObject *op)
 189{
 190	_PyObject_GC_UNTRACK(op);
 191	Py_DECREF(op->cl_bases);
 192	Py_DECREF(op->cl_dict);
 193	Py_XDECREF(op->cl_name);
 194	Py_XDECREF(op->cl_getattr);
 195	Py_XDECREF(op->cl_setattr);
 196	Py_XDECREF(op->cl_delattr);
 197	PyObject_GC_Del(op);
 198}
 199
 200static PyObject *
 201class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
 202{
 203	Py_ssize_t i, n;
 204	PyObject *value = PyDict_GetItem(cp->cl_dict, name);
 205	if (value != NULL) {
 206		*pclass = cp;
 207		return value;
 208	}
 209	n = PyTuple_Size(cp->cl_bases);
 210	for (i = 0; i < n; i++) {
 211		/* XXX What if one of the bases is not a class? */
 212		PyObject *v = class_lookup(
 213			(PyClassObject *)
 214			PyTuple_GetItem(cp->cl_bases, i), name, pclass);
 215		if (v != NULL)
 216			return v;
 217	}
 218	return NULL;
 219}
 220
 221static PyObject *
 222class_getattr(register PyClassObject *op, PyObject *name)
 223{
 224	register PyObject *v;
 225	register char *sname = PyString_AsString(name);
 226	PyClassObject *klass;
 227	descrgetfunc f;
 228
 229	if (sname[0] == '_' && sname[1] == '_') {
 230		if (strcmp(sname, "__dict__") == 0) {
 231			if (PyEval_GetRestricted()) {
 232				PyErr_SetString(PyExc_RuntimeError,
 233			   "class.__dict__ not accessible in restricted mode");
 234				return NULL;
 235			}
 236			Py_INCREF(op->cl_dict);
 237			return op->cl_dict;
 238		}
 239		if (strcmp(sname, "__bases__") == 0) {
 240			Py_INCREF(op->cl_bases);
 241			return op->cl_bases;
 242		}
 243		if (strcmp(sname, "__name__") == 0) {
 244			if (op->cl_name == NULL)
 245				v = Py_None;
 246			else
 247				v = op->cl_name;
 248			Py_INCREF(v);
 249			return v;
 250		}
 251	}
 252	v = class_lookup(op, name, &klass);
 253	if (v == NULL) {
 254		PyErr_Format(PyExc_AttributeError,
 255			     "class %.50s has no attribute '%.400s'",
 256			     PyString_AS_STRING(op->cl_name), sname);
 257		return NULL;
 258	}
 259	f = TP_DESCR_GET(v->ob_type);
 260	if (f == NULL)
 261		Py_INCREF(v);
 262	else
 263		v = f(v, (PyObject *)NULL, (PyObject *)op);
 264	return v;
 265}
 266
 267static void
 268set_slot(PyObject **slot, PyObject *v)
 269{
 270	PyObject *temp = *slot;
 271	Py_XINCREF(v);
 272	*slot = v;
 273	Py_XDECREF(temp);
 274}
 275
 276static void
 277set_attr_slots(PyClassObject *c)
 278{
 279	PyClassObject *dummy;
 280
 281	set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
 282	set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
 283	set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
 284}
 285
 286static char *
 287set_dict(PyClassObject *c, PyObject *v)
 288{
 289	if (v == NULL || !PyDict_Check(v))
 290		return "__dict__ must be a dictionary object";
 291	set_slot(&c->cl_dict, v);
 292	set_attr_slots(c);
 293	return "";
 294}
 295
 296static char *
 297set_bases(PyClassObject *c, PyObject *v)
 298{
 299	Py_ssize_t i, n;
 300
 301	if (v == NULL || !PyTuple_Check(v))
 302		return "__bases__ must be a tuple object";
 303	n = PyTuple_Size(v);
 304	for (i = 0; i < n; i++) {
 305		PyObject *x = PyTuple_GET_ITEM(v, i);
 306		if (!PyClass_Check(x))
 307			return "__bases__ items must be classes";
 308		if (PyClass_IsSubclass(x, (PyObject *)c))
 309			return "a __bases__ item causes an inheritance cycle";
 310	}
 311	set_slot(&c->cl_bases, v);
 312	set_attr_slots(c);
 313	return "";
 314}
 315
 316static char *
 317set_name(PyClassObject *c, PyObject *v)
 318{
 319	if (v == NULL || !PyString_Check(v))
 320		return "__name__ must be a string object";
 321	if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
 322		return "__name__ must not contain null bytes";
 323	set_slot(&c->cl_name, v);
 324	return "";
 325}
 326
 327static int
 328class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
 329{
 330	char *sname;
 331	if (PyEval_GetRestricted()) {
 332		PyErr_SetString(PyExc_RuntimeError,
 333			   "classes are read-only in restricted mode");
 334		return -1;
 335	}
 336	sname = PyString_AsString(name);
 337	if (sname[0] == '_' && sname[1] == '_') {
 338		Py_ssize_t n = PyString_Size(name);
 339		if (sname[n-1] == '_' && sname[n-2] == '_') {
 340			char *err = NULL;
 341			if (strcmp(sname, "__dict__") == 0)
 342				err = set_dict(op, v);
 343			else if (strcmp(sname, "__bases__") == 0)
 344				err = set_bases(op, v);
 345			else if (strcmp(sname, "__name__") == 0)
 346				err = set_name(op, v);
 347			else if (strcmp(sname, "__getattr__") == 0)
 348				set_slot(&op->cl_getattr, v);
 349			else if (strcmp(sname, "__setattr__") == 0)
 350				set_slot(&op->cl_setattr, v);
 351			else if (strcmp(sname, "__delattr__") == 0)
 352				set_slot(&op->cl_delattr, v);
 353			/* For the last three, we fall through to update the
 354			   dictionary as well. */
 355			if (err != NULL) {
 356				if (*err == '\0')
 357					return 0;
 358				PyErr_SetString(PyExc_TypeError, err);
 359				return -1;
 360			}
 361		}
 362	}
 363	if (v == NULL) {
 364		int rv = PyDict_DelItem(op->cl_dict, name);
 365		if (rv < 0)
 366			PyErr_Format(PyExc_AttributeError,
 367				     "class %.50s has no attribute '%.400s'",
 368				     PyString_AS_STRING(op->cl_name), sname);
 369		return rv;
 370	}
 371	else
 372		return PyDict_SetItem(op->cl_dict, name, v);
 373}
 374
 375static PyObject *
 376class_repr(PyClassObject *op)
 377{
 378	PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
 379	char *name;
 380	if (op->cl_name == NULL || !PyString_Check(op->cl_name))
 381		name = "?";
 382	else
 383		name = PyString_AsString(op->cl_name);
 384	if (mod == NULL || !PyString_Check(mod))
 385		return PyString_FromFormat("<class ?.%s at %p>", name, op);
 386	else
 387		return PyString_FromFormat("<class %s.%s at %p>",
 388					   PyString_AsString(mod),
 389					   name, op);
 390}
 391
 392static PyObject *
 393class_str(PyClassObject *op)
 394{
 395	PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
 396	PyObject *name = op->cl_name;
 397	PyObject *res;
 398	Py_ssize_t m, n;
 399
 400	if (name == NULL || !PyString_Check(name))
 401		return class_repr(op);
 402	if (mod == NULL || !PyString_Check(mod)) {
 403		Py_INCREF(name);
 404		return name;
 405	}
 406	m = PyString_GET_SIZE(mod);
 407	n = PyString_GET_SIZE(name);
 408	res = PyString_FromStringAndSize((char *)NULL, m+1+n);
 409	if (res != NULL) {
 410		char *s = PyString_AS_STRING(res);
 411		memcpy(s, PyString_AS_STRING(mod), m);
 412		s += m;
 413		*s++ = '.';
 414		memcpy(s, PyString_AS_STRING(name), n);
 415	}
 416	return res;
 417}
 418
 419static int
 420class_traverse(PyClassObject *o, visitproc visit, void *arg)
 421{
 422	Py_VISIT(o->cl_bases);
 423	Py_VISIT(o->cl_dict);
 424	Py_VISIT(o->cl_name);
 425	Py_VISIT(o->cl_getattr);
 426	Py_VISIT(o->cl_setattr);
 427	Py_VISIT(o->cl_delattr);
 428	return 0;
 429}
 430
 431PyTypeObject PyClass_Type = {
 432	PyObject_HEAD_INIT(&PyType_Type)
 433	0,
 434	"classobj",
 435	sizeof(PyClassObject),
 436	0,
 437	(destructor)class_dealloc,		/* tp_dealloc */
 438	0,					/* tp_print */
 439	0,					/* tp_getattr */
 440	0,					/* tp_setattr */
 441	0,					/* tp_compare */
 442	(reprfunc)class_repr,			/* tp_repr */
 443	0,					/* tp_as_number */
 444	0,					/* tp_as_sequence */
 445	0,					/* tp_as_mapping */
 446	0,					/* tp_hash */
 447	PyInstance_New,				/* tp_call */
 448	(reprfunc)class_str,			/* tp_str */
 449	(getattrofunc)class_getattr,		/* tp_getattro */
 450	(setattrofunc)class_setattr,		/* tp_setattro */
 451	0,					/* tp_as_buffer */
 452	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
 453	class_doc,				/* tp_doc */
 454	(traverseproc)class_traverse,		/* tp_traverse */
 455 	0,					/* tp_clear */
 456	0,					/* tp_richcompare */
 457	0,					/* tp_weaklistoffset */
 458	0,					/* tp_iter */
 459	0,					/* tp_iternext */
 460	0,					/* tp_methods */
 461	0,					/* tp_members */
 462	0,					/* tp_getset */
 463	0,					/* tp_base */
 464	0,					/* tp_dict */
 465	0,					/* tp_descr_get */
 466	0,					/* tp_descr_set */
 467	0,					/* tp_dictoffset */
 468	0,					/* tp_init */
 469	0,					/* tp_alloc */
 470	class_new,				/* tp_new */
 471};
 472
 473int
 474PyClass_IsSubclass(PyObject *klass, PyObject *base)
 475{
 476	Py_ssize_t i, n;
 477	PyClassObject *cp;
 478	if (klass == base)
 479		return 1;
 480	if (PyTuple_Check(base)) {
 481		n = PyTuple_GET_SIZE(base);
 482		for (i = 0; i < n; i++) {
 483			if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
 484				return 1;
 485		}
 486		return 0;
 487	}
 488	if (klass == NULL || !PyClass_Check(klass))
 489		return 0;
 490	cp = (PyClassObject *)klass;
 491	n = PyTuple_Size(cp->cl_bases);
 492	for (i = 0; i < n; i++) {
 493		if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
 494			return 1;
 495	}
 496	return 0;
 497}
 498
 499
 500/* Instance objects */
 501
 502PyObject *
 503PyInstance_NewRaw(PyObject *klass, PyObject *dict)
 504{
 505	PyInstanceObject *inst;
 506
 507	if (!PyClass_Check(klass)) {
 508		PyErr_BadInternalCall();
 509		return NULL;
 510	}
 511	if (dict == NULL) {
 512		dict = PyDict_New();
 513		if (dict == NULL)
 514			return NULL;
 515	}
 516	else {
 517		if (!PyDict_Check(dict)) {
 518			PyErr_BadInternalCall();
 519			return NULL;
 520		}
 521		Py_INCREF(dict);
 522	}
 523	inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
 524	if (inst == NULL) {
 525		Py_DECREF(dict);
 526		return NULL;
 527	}
 528	inst->in_weakreflist = NULL;
 529	Py_INCREF(klass);
 530	inst->in_class = (PyClassObject *)klass;
 531	inst->in_dict = dict;
 532	_PyObject_GC_TRACK(inst);
 533	return (PyObject *)inst;
 534}
 535
 536PyObject *
 537PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
 538{
 539	register PyInstanceObject *inst;
 540	PyObject *init;
 541	static PyObject *initstr;
 542
 543	if (initstr == NULL) {
 544		initstr = PyString_InternFromString("__init__");
 545		if (initstr == NULL)
 546			return NULL;
 547	}
 548	inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
 549	if (inst == NULL)
 550		return NULL;
 551	init = instance_getattr2(inst, initstr);
 552	if (init == NULL) {
 553		if (PyErr_Occurred()) {
 554			Py_DECREF(inst);
 555			return NULL;
 556		}
 557		if ((arg != NULL && (!PyTuple_Check(arg) ||
 558				     PyTuple_Size(arg) != 0))
 559		    || (kw != NULL && (!PyDict_Check(kw) ||
 560				      PyDict_Size(kw) != 0))) {
 561			PyErr_SetString(PyExc_TypeError,
 562				   "this constructor takes no arguments");
 563			Py_DECREF(inst);
 564			inst = NULL;
 565		}
 566	}
 567	else {
 568		PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
 569		Py_DECREF(init);
 570		if (res == NULL) {
 571			Py_DECREF(inst);
 572			inst = NULL;
 573		}
 574		else {
 575			if (res != Py_None) {
 576				PyErr_SetString(PyExc_TypeError,
 577					   "__init__() should return None");
 578				Py_DECREF(inst);
 579				inst = NULL;
 580			}
 581			Py_DECREF(res);
 582		}
 583	}
 584	return (PyObject *)inst;
 585}
 586
 587/* Instance methods */
 588
 589PyDoc_STRVAR(instance_doc,
 590"instance(class[, dict])\n\
 591\n\
 592Create an instance without calling its __init__() method.\n\
 593The class must be a classic class.\n\
 594If present, dict must be a dictionary or None.");
 595
 596static PyObject *
 597instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
 598{
 599	PyObject *klass;
 600	PyObject *dict = Py_None;
 601
 602	if (!PyArg_ParseTuple(args, "O!|O:instance",
 603			      &PyClass_Type, &klass, &dict))
 604		return NULL;
 605
 606	if (dict == Py_None)
 607		dict = NULL;
 608	else if (!PyDict_Check(dict)) {
 609		PyErr_SetString(PyExc_TypeError,
 610		      "instance() second arg must be dictionary or None");
 611		return NULL;
 612	}
 613	return PyInstance_NewRaw(klass, dict);
 614}
 615
 616
 617static void
 618instance_dealloc(register PyInstanceObject *inst)
 619{
 620	PyObject *error_type, *error_value, *error_traceback;
 621	PyObject *del;
 622	static PyObject *delstr;
 623
 624	_PyObject_GC_UNTRACK(inst);
 625	if (inst->in_weakreflist != NULL)
 626		PyObject_ClearWeakRefs((PyObject *) inst);
 627
 628	/* Temporarily resurrect the object. */
 629	assert(inst->ob_type == &PyInstance_Type);
 630	assert(inst->ob_refcnt == 0);
 631	inst->ob_refcnt = 1;
 632
 633	/* Save the current exception, if any. */
 634	PyErr_Fetch(&error_type, &error_value, &error_traceback);
 635	/* Execute __del__ method, if any. */
 636	if (delstr == NULL) {
 637		delstr = PyString_InternFromString("__del__");
 638		if (delstr == NULL)
 639			PyErr_WriteUnraisable((PyObject*)inst);
 640	}
 641	if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
 642		PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
 643		if (res == NULL)
 644			PyErr_WriteUnraisable(del);
 645		else
 646			Py_DECREF(res);
 647		Py_DECREF(del);
 648	}
 649	/* Restore the saved exception. */
 650	PyErr_Restore(error_type, error_value, error_traceback);
 651
 652	/* Undo the temporary resurrection; can't use DECREF here, it would
 653	 * cause a recursive call.
 654	 */
 655	assert(inst->ob_refcnt > 0);
 656	if (--inst->ob_refcnt == 0) {
 657
 658		/* New weakrefs could be created during the finalizer call.
 659		    If this occurs, clear them out without calling their
 660		    finalizers since they might rely on part of the object
 661		    being finalized that has already been destroyed. */
 662		while (inst->in_weakreflist != NULL) {
 663			_PyWeakref_ClearRef((PyWeakReference *)
 664                                            (inst->in_weakreflist));
 665		}
 666
 667		Py_DECREF(inst->in_class);
 668		Py_XDECREF(inst->in_dict);
 669		PyObject_GC_Del(inst);
 670	}
 671	else {
 672		Py_ssize_t refcnt = inst->ob_refcnt;
 673		/* __del__ resurrected it!  Make it look like the original
 674		 * Py_DECREF never happened.
 675		 */
 676		_Py_NewReference((PyObject *)inst);
 677		inst->ob_refcnt = refcnt;
 678		_PyObject_GC_TRACK(inst);
 679		/* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
 680		 * we need to undo that. */
 681		_Py_DEC_REFTOTAL;
 682		/* If Py_TRACE_REFS, _Py_NewReference re-added self to the
 683		 * object chain, so no more to do there.
 684		 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
 685		 * _Py_NewReference bumped tp_allocs: both of those need to be
 686		 * undone.
 687		 */
 688#ifdef COUNT_ALLOCS
 689		--inst->ob_type->tp_frees;
 690		--inst->ob_type->tp_allocs;
 691#endif
 692	}
 693}
 694
 695static PyObject *
 696instance_getattr1(register PyInstanceObject *inst, PyObject *name)
 697{
 698	register PyObject *v;
 699	register char *sname = PyString_AsString(name);
 700	if (sname[0] == '_' && sname[1] == '_') {
 701		if (strcmp(sname, "__dict__") == 0) {
 702			if (PyEval_GetRestricted()) {
 703				PyErr_SetString(PyExc_RuntimeError,
 704			"instance.__dict__ not accessible in restricted mode");
 705				return NULL;
 706			}
 707			Py_INCREF(inst->in_dict);
 708			return inst->in_dict;
 709		}
 710		if (strcmp(sname, "__class__") == 0) {
 711			Py_INCREF(inst->in_class);
 712			return (PyObject *)inst->in_class;
 713		}
 714	}
 715	v = instance_getattr2(inst, name);
 716	if (v == NULL && !PyErr_Occurred()) {
 717		PyErr_Format(PyExc_AttributeError,
 718			     "%.50s instance has no attribute '%.400s'",
 719			     PyString_AS_STRING(inst->in_class->cl_name), sname);
 720	}
 721	return v;
 722}
 723
 724static PyObject *
 725instance_getattr2(register PyInstanceObject *inst, PyObject *name)
 726{
 727	register PyObject *v;
 728	PyClassObject *klass;
 729	descrgetfunc f;
 730
 731	v = PyDict_GetItem(inst->in_dict, name);
 732	if (v != NULL) {
 733		Py_INCREF(v);
 734		return v;
 735	}
 736	v = class_lookup(inst->in_class, name, &klass);
 737	if (v != NULL) {
 738		Py_INCREF(v);
 739		f = TP_DESCR_GET(v->ob_type);
 740		if (f != NULL) {
 741			PyObject *w = f(v, (PyObject *)inst,
 742					(PyObject *)(inst->in_class));
 743			Py_DECREF(v);
 744			v = w;
 745		}
 746	}
 747	return v;
 748}
 749
 750static PyObject *
 751instance_getattr(register PyInstanceObject *inst, PyObject *name)
 752{
 753	register PyObject *func, *res;
 754	res = instance_getattr1(inst, name);
 755	if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
 756		PyObject *args;
 757		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 758			return NULL;
 759		PyErr_Clear();
 760		args = PyTuple_Pack(2, inst, name);
 761		if (args == NULL)
 762			return NULL;
 763		res = PyEval_CallObject(func, args);
 764		Py_DECREF(args);
 765	}
 766	return res;
 767}
 768
 769/* See classobject.h comments:  this only does dict lookups, and is always
 770 * safe to call.
 771 */
 772PyObject *
 773_PyInstance_Lookup(PyObject *pinst, PyObject *name)
 774{
 775	PyObject *v;
 776	PyClassObject *klass;
 777	PyInstanceObject *inst;	/* pinst cast to the right type */
 778
 779	assert(PyInstance_Check(pinst));
 780	inst = (PyInstanceObject *)pinst;
 781
 782	assert(PyString_Check(name));
 783
 784 	v = PyDict_GetItem(inst->in_dict, name);
 785	if (v == NULL)
 786		v = class_lookup(inst->in_class, name, &klass);
 787	return v;
 788}
 789
 790static int
 791instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
 792{
 793	if (v == NULL) {
 794		int rv = PyDict_DelItem(inst->in_dict, name);
 795		if (rv < 0)
 796			PyErr_Format(PyExc_AttributeError,
 797				     "%.50s instance has no attribute '%.400s'",
 798				     PyString_AS_STRING(inst->in_class->cl_name),
 799				     PyString_AS_STRING(name));
 800		return rv;
 801	}
 802	else
 803		return PyDict_SetItem(inst->in_dict, name, v);
 804}
 805
 806static int
 807instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
 808{
 809	PyObject *func, *args, *res, *tmp;
 810	char *sname = PyString_AsString(name);
 811	if (sname[0] == '_' && sname[1] == '_') {
 812		Py_ssize_t n = PyString_Size(name);
 813		if (sname[n-1] == '_' && sname[n-2] == '_') {
 814			if (strcmp(sname, "__dict__") == 0) {
 815				if (PyEval_GetRestricted()) {
 816					PyErr_SetString(PyExc_RuntimeError,
 817				 "__dict__ not accessible in restricted mode");
 818					return -1;
 819				}
 820				if (v == NULL || !PyDict_Check(v)) {
 821				    PyErr_SetString(PyExc_TypeError,
 822				       "__dict__ must be set to a dictionary");
 823				    return -1;
 824				}
 825				tmp = inst->in_dict;
 826				Py_INCREF(v);
 827				inst->in_dict = v;
 828				Py_DECREF(tmp);
 829				return 0;
 830			}
 831			if (strcmp(sname, "__class__") == 0) {
 832				if (PyEval_GetRestricted()) {
 833					PyErr_SetString(PyExc_RuntimeError,
 834				"__class__ not accessible in restricted mode");
 835					return -1;
 836				}
 837				if (v == NULL || !PyClass_Check(v)) {
 838					PyErr_SetString(PyExc_TypeError,
 839					   "__class__ must be set to a class");
 840					return -1;
 841				}
 842				tmp = (PyObject *)(inst->in_class);
 843				Py_INCREF(v);
 844				inst->in_class = (PyClassObject *)v;
 845				Py_DECREF(tmp);
 846				return 0;
 847			}
 848		}
 849	}
 850	if (v == NULL)
 851		func = inst->in_class->cl_delattr;
 852	else
 853		func = inst->in_class->cl_setattr;
 854	if (func == NULL)
 855		return instance_setattr1(inst, name, v);
 856	if (v == NULL)
 857		args = PyTuple_Pack(2, inst, name);
 858	else
 859		args = PyTuple_Pack(3, inst, name, v);
 860	if (args == NULL)
 861		return -1;
 862	res = PyEval_CallObject(func, args);
 863	Py_DECREF(args);
 864	if (res == NULL)
 865		return -1;
 866	Py_DECREF(res);
 867	return 0;
 868}
 869
 870static PyObject *
 871instance_repr(PyInstanceObject *inst)
 872{
 873	PyObject *func;
 874	PyObject *res;
 875	static PyObject *reprstr;
 876
 877	if (reprstr == NULL) {
 878		reprstr = PyString_InternFromString("__repr__");
 879		if (reprstr == NULL)
 880			return NULL;
 881	}
 882	func = instance_getattr(inst, reprstr);
 883	if (func == NULL) {
 884		PyObject *classname, *mod;
 885		char *cname;
 886		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 887			return NULL;
 888		PyErr_Clear();
 889		classname = inst->in_class->cl_name;
 890		mod = PyDict_GetItemString(inst->in_class->cl_dict,
 891					   "__module__");
 892		if (classname != NULL && PyString_Check(classname))
 893			cname = PyString_AsString(classname);
 894		else
 895			cname = "?";
 896		if (mod == NULL || !PyString_Check(mod))
 897			return PyString_FromFormat("<?.%s instance at %p>",
 898						   cname, inst);
 899		else
 900			return PyString_FromFormat("<%s.%s instance at %p>",
 901						   PyString_AsString(mod),
 902						   cname, inst);
 903	}
 904	res = PyEval_CallObject(func, (PyObject *)NULL);
 905	Py_DECREF(func);
 906	return res;
 907}
 908
 909static PyObject *
 910instance_str(PyInstanceObject *inst)
 911{
 912	PyObject *func;
 913	PyObject *res;
 914	static PyObject *strstr;
 915
 916	if (strstr == NULL) {
 917		strstr = PyString_InternFromString("__str__");
 918		if (strstr == NULL)
 919			return NULL;
 920	}
 921	func = instance_getattr(inst, strstr);
 922	if (func == NULL) {
 923		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 924			return NULL;
 925		PyErr_Clear();
 926		return instance_repr(inst);
 927	}
 928	res = PyEval_CallObject(func, (PyObject *)NULL);
 929	Py_DECREF(func);
 930	return res;
 931}
 932
 933static long
 934instance_hash(PyInstanceObject *inst)
 935{
 936	PyObject *func;
 937	PyObject *res;
 938	long outcome;
 939	static PyObject *hashstr, *eqstr, *cmpstr;
 940
 941	if (hashstr == NULL) {
 942		hashstr = PyString_InternFromString("__hash__");
 943		if (hashstr == NULL)
 944			return -1;
 945	}
 946	func = instance_getattr(inst, hashstr);
 947	if (func == NULL) {
 948		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 949			return -1;
 950		PyErr_Clear();
 951		/* If there is no __eq__ and no __cmp__ method, we hash on the
 952		   address.  If an __eq__ or __cmp__ method exists, there must
 953		   be a __hash__. */
 954		if (eqstr == NULL) {
 955			eqstr = PyString_InternFromString("__eq__");
 956			if (eqstr == NULL)
 957				return -1;
 958		}
 959		func = instance_getattr(inst, eqstr);
 960		if (func == NULL) {
 961			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 962				return -1;
 963			PyErr_Clear();
 964			if (cmpstr == NULL) {
 965				cmpstr = PyString_InternFromString("__cmp__");
 966				if (cmpstr == NULL)
 967					return -1;
 968			}
 969			func = instance_getattr(inst, cmpstr);
 970			if (func == NULL) {
 971				if (!PyErr_ExceptionMatches(
 972					PyExc_AttributeError))
 973					return -1;
 974				PyErr_Clear();
 975				return _Py_HashPointer(inst);
 976			}
 977		}
 978		Py_XDECREF(func);
 979		PyErr_SetString(PyExc_TypeError, "unhashable instance");
 980		return -1;
 981	}
 982	res = PyEval_CallObject(func, (PyObject *)NULL);
 983	Py_DECREF(func);
 984	if (res == NULL)
 985		return -1;
 986	if (PyInt_Check(res) || PyLong_Check(res))
 987		/* This already converts a -1 result to -2. */
 988		outcome = res->ob_type->tp_hash(res);
 989	else {
 990		PyErr_SetString(PyExc_TypeError,
 991				"__hash__() should return an int");
 992		outcome = -1;
 993	}
 994	Py_DECREF(res);
 995	return outcome;
 996}
 997
 998static int
 999instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
1000{
1001	Py_VISIT(o->in_class);
1002	Py_VISIT(o->in_dict);
1003	return 0;
1004}
1005
1006static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
1007static PyObject *iterstr, *nextstr;
1008
1009static Py_ssize_t
1010instance_length(PyInstanceObject *inst)
1011{
1012	PyObject *func;
1013	PyObject *res;
1014	Py_ssize_t outcome;
1015
1016	if (lenstr == NULL) {
1017		lenstr = PyString_InternFromString("__len__");
1018		if (lenstr == NULL)
1019			return -1;
1020	}
1021	func = instance_getattr(inst, lenstr);
1022	if (func == NULL)
1023		return -1;
1024	res = PyEval_CallObject(func, (PyObject *)NULL);
1025	Py_DECREF(func);
1026	if (res == NULL)
1027		return -1;
1028	if (PyInt_Check(res)) {
1029		outcome = PyInt_AsSsize_t(res);
1030		if (outcome == -1 && PyErr_Occurred()) {
1031			Py_DECREF(res);
1032			return -1;
1033		}
1034#if SIZEOF_SIZE_T < SIZEOF_INT
1035		/* Overflow check -- range of PyInt is more than C int */
1036		if (outcome != (int)outcome) {
1037			PyErr_SetString(PyExc_OverflowError,
1038			 "__len__() should return 0 <= outcome < 2**31");
1039			outcome = -1;
1040		}
1041		else
1042#endif
1043		if (outcome < 0) {
1044			PyErr_SetString(PyExc_ValueError,
1045					"__len__() should return >= 0");
1046			outcome = -1;
1047		}
1048	}
1049	else {
1050		PyErr_SetString(PyExc_TypeError,
1051				"__len__() should return an int");
1052		outcome = -1;
1053	}
1054	Py_DECREF(res);
1055	return outcome;
1056}
1057
1058static PyObject *
1059instance_subscript(PyInstanceObject *inst, PyObject *key)
1060{
1061	PyObject *func;
1062	PyObject *arg;
1063	PyObject *res;
1064
1065	if (getitemstr == NULL) {
1066		getitemstr = PyString_InternFromString("__getitem__");
1067		if (getitemstr == NULL)
1068			return NULL;
1069	}
1070	func = instance_getattr(inst, getitemstr);
1071	if (func == NULL)
1072		return NULL;
1073	arg = PyTuple_Pack(1, key);
1074	if (arg == NULL) {
1075		Py_DECREF(func);
1076		return NULL;
1077	}
1078	res = PyEval_CallObject(func, arg);
1079	Py_DECREF(func);
1080	Py_DECREF(arg);
1081	return res;
1082}
1083
1084static int
1085instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
1086{
1087	PyObject *func;
1088	PyObject *arg;
1089	PyObject *res;
1090
1091	if (value == NULL) {
1092		if (delitemstr == NULL) {
1093			delitemstr = PyString_InternFromString("__delitem__");
1094			if (delitemstr == NULL)
1095				return -1;
1096		}
1097		func = instance_getattr(inst, delitemstr);
1098	}
1099	else {
1100		if (setitemstr == NULL) {
1101			setitemstr = PyString_InternFromString("__setitem__");
1102			if (setitemstr == NULL)
1103				return -1;
1104		}
1105		func = instance_getattr(inst, setitemstr);
1106	}
1107	if (func == NULL)
1108		return -1;
1109	if (value == NULL)
1110		arg = PyTuple_Pack(1, key);
1111	else
1112		arg = PyTuple_Pack(2, key, value);
1113	if (arg == NULL) {
1114		Py_DECREF(func);
1115		return -1;
1116	}
1117	res = PyEval_CallObject(func, arg);
1118	Py_DECREF(func);
1119	Py_DECREF(arg);
1120	if (res == NULL)
1121		return -1;
1122	Py_DECREF(res);
1123	return 0;
1124}
1125
1126static PyMappingMethods instance_as_mapping = {
1127	(lenfunc)instance_length,		/* mp_length */
1128	(binaryfunc)instance_subscript,		/* mp_subscript */
1129	(objobjargproc)instance_ass_subscript,	/* mp_ass_subscript */
1130};
1131
1132static PyObject *
1133instance_item(PyInstanceObject *inst, Py_ssize_t i)
1134{
1135	PyObject *func, *res;
1136
1137	if (getitemstr == NULL) {
1138		getitemstr = PyString_InternFromString("__getitem__");
1139		if (getitemstr == NULL)
1140			return NULL;
1141	}
1142	func = instance_getattr(inst, getitemstr);
1143	if (func == NULL)
1144		return NULL;
1145	res = PyObject_CallFunction(func, "n", i);
1146	Py_DECREF(func);
1147	return res;
1148}
1149
1150static PyObject *
1151instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
1152{
1153	PyObject *func, *arg, *res;
1154	static PyObject *getslicestr;
1155
1156	if (getslicestr == NULL) {
1157		getslicestr = PyString_InternFromString("__getslice__");
1158		if (getslicestr == NULL)
1159			return NULL;
1160	}
1161	func = instance_getattr(inst, getslicestr);
1162
1163	if (func == NULL) {
1164		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1165			return NULL;
1166		PyErr_Clear();
1167
1168		if (getitemstr == NULL) {
1169			getitemstr = PyString_InternFromString("__getitem__");
1170			if (getitemstr == NULL)
1171				return NULL;
1172		}
1173		func = instance_getattr(inst, getitemstr);
1174		if (func == NULL)
1175			return NULL;
1176		arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
1177	}
1178	else {
1179		if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
1180				   "use __getitem__", 1) < 0) {
1181			Py_DECREF(func);
1182			return NULL;
1183		}
1184		arg = Py_BuildValue("(nn)", i, j);
1185	}
1186
1187	if (arg == NULL) {
1188		Py_DECREF(func);
1189		return NULL;
1190	}
1191	res = PyEval_CallObject(func, arg);
1192	Py_DECREF(func);
1193	Py_DECREF(arg);
1194	return res;
1195}
1196
1197static int
1198instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
1199{
1200	PyObject *func, *arg, *res;
1201
1202	if (item == NULL) {
1203		if (delitemstr == NULL) {
1204			delitemstr = PyString_InternFromString("__delitem__");
1205			if (delitemstr == NULL)
1206				return -1;
1207		}
1208		func = instance_getattr(inst, delitemstr);
1209	}
1210	else {
1211		if (setitemstr == NULL) {
1212			setitemstr = PyString_InternFromString("__setitem__");
1213			if (setitemstr == NULL)
1214				return -1;
1215		}
1216		func = instance_getattr(inst, setitemstr);
1217	}
1218	if (func == NULL)
1219		return -1;
1220	if (item == NULL)
1221		arg = PyInt_FromSsize_t(i);
1222	else
1223		arg = Py_BuildValue("(nO)", i, item);
1224	if (arg == NULL) {
1225		Py_DECREF(func);
1226		return -1;
1227	}
1228	res = PyEval_CallObject(func, arg);
1229	Py_DECREF(func);
1230	Py_DECREF(arg);
1231	if (res == NULL)
1232		return -1;
1233	Py_DECREF(res);
1234	return 0;
1235}
1236
1237static int
1238instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
1239{
1240	PyObject *func, *arg, *res;
1241	static PyObject *setslicestr, *delslicestr;
1242
1243	if (value == NULL) {
1244		if (delslicestr == NULL) {
1245			delslicestr =
1246				PyString_InternFromString("__delslice__");
1247			if (delslicestr == NULL)
1248				return -1;
1249		}
1250		func = instance_getattr(inst, delslicestr);
1251		if (func == NULL) {
1252			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1253				return -1;
1254			PyErr_Clear();
1255			if (delitemstr == NULL) {
1256				delitemstr =
1257				    PyString_InternFromString("__delitem__");
1258				if (delitemstr == NULL)
1259					return -1;
1260			}
1261			func = instance_getattr(inst, delitemstr);
1262			if (func == NULL)
1263				return -1;
1264
1265			arg = Py_BuildValue("(N)",
1266					    _PySlice_FromIndices(i, j));
1267		}
1268		else {
1269			if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
1270				            "removed; use __delitem__", 1) < 0) {
1271				Py_DECREF(func);
1272				return -1;
1273			}
1274			arg = Py_BuildValue("(nn)", i, j);
1275		}
1276	}
1277	else {
1278		if (setslicestr == NULL) {
1279			setslicestr =
1280				PyString_InternFromString("__setslice__");
1281			if (setslicestr == NULL)
1282				return -1;
1283		}
1284		func = instance_getattr(inst, setslicestr);
1285		if (func == NULL) {
1286			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1287				return -1;
1288			PyErr_Clear();
1289			if (setitemstr == NULL) {
1290				setitemstr =
1291				    PyString_InternFromString("__setitem__");
1292				if (setitemstr == NULL)
1293					return -1;
1294			}
1295			func = instance_getattr(inst, setitemstr);
1296			if (func == NULL)
1297				return -1;
1298
1299			arg = Py_BuildValue("(NO)",
1300					    _PySlice_FromIndices(i, j), value);
1301		}
1302		else {
1303			if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
1304					   "removed; use __setitem__", 1) < 0) {
1305				Py_DECREF(func);
1306				return -1;
1307			}
1308			arg = Py_BuildValue("(nnO)", i, j, value);
1309		}
1310	}
1311	if (arg == NULL) {
1312		Py_DECREF(func);
1313		return -1;
1314	}
1315	res = PyEval_CallObject(func, arg);
1316	Py_DECREF(func);
1317	Py_DECREF(arg);
1318	if (res == NULL)
1319		return -1;
1320	Py_DECREF(res);
1321	return 0;
1322}
1323
1324static int
1325instance_contains(PyInstanceObject *inst, PyObject *member)
1326{
1327	static PyObject *__contains__;
1328	PyObject *func;
1329
1330	/* Try __contains__ first.
1331	 * If that can't be done, try iterator-based searching.
1332	 */
1333
1334	if(__contains__ == NULL) {
1335		__contains__ = PyString_InternFromString("__contains__");
1336		if(__contains__ == NULL)
1337			return -1;
1338	}
1339	func = instance_getattr(inst, __contains__);
1340	if (func) {
1341		PyObject *res;
1342		int ret;
1343		PyObject *arg = PyTuple_Pack(1, member);
1344		if(arg == NULL) {
1345			Py_DECREF(func);
1346			return -1;
1347		}
1348		res = PyEval_CallObject(func, arg);
1349		Py_DECREF(func);
1350		Py_DECREF(arg);
1351		if(res == NULL)
1352			return -1;
1353		ret = PyObject_IsTrue(res);
1354		Py_DECREF(res);
1355		return ret;
1356	}
1357
1358	/* Couldn't find __contains__. */
1359	if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
1360		Py_ssize_t rc;
1361		/* Assume the failure was simply due to that there is no
1362		 * __contains__ attribute, and try iterating instead.
1363		 */
1364		PyErr_Clear();
1365		rc = _PySequence_IterSearch((PyObject *)inst, member,
1366					    PY_ITERSEARCH_CONTAINS);
1367		if (rc >= 0)
1368			return rc > 0;
1369	}
1370	return -1;
1371}
1372
1373static PySequenceMethods
1374instance_as_sequence = {
1375	(lenfunc)instance_length,		/* sq_length */
1376	0,					/* sq_concat */
1377	0,					/* sq_repeat */
1378	(ssizeargfunc)instance_item,		/* sq_item */
1379	(ssizessizeargfunc)instance_slice,	/* sq_slice */
1380	(ssizeobjargproc)instance_ass_item,	/* sq_ass_item */
1381	(ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
1382	(objobjproc)instance_contains,		/* sq_contains */
1383};
1384
1385static PyObject *
1386generic_unary_op(PyInstanceObject *self, PyObject *methodname)
1387{
1388	PyObject *func, *res;
1389
1390	if ((func = instance_getattr(self, methodname)) == NULL)
1391		return NULL;
1392	res = PyEval_CallObject(func, (PyObject *)NULL);
1393	Py_DECREF(func);
1394	return res;
1395}
1396
1397static PyObject *
1398generic_binary_op(PyObject *v, PyObject *w, char *opname)
1399{
1400	PyObject *result;
1401	PyObject *args;
1402	PyObject *func = PyObject_GetAttrString(v, opname);
1403	if (func == NULL) {
1404		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1405			return NULL;
1406		PyErr_Clear();
1407		Py_INCREF(Py_NotImplemented);
1408		return Py_NotImplemented;
1409	}
1410	args = PyTuple_Pack(1, w);
1411	if (args == NULL) {
1412		Py_DECREF(func);
1413		return NULL;
1414	}
1415	result = PyEval_CallObject(func, args);
1416	Py_DECREF(args);
1417	Py_DECREF(func);
1418	return result;
1419}
1420
1421
1422static PyObject *coerce_obj;
1423
1424/* Try one half of a binary operator involving a class instance. */
1425static PyObject *
1426half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
1427		int swapped)
1428{
1429	PyObject *args;
1430	PyObject *coercefunc;
1431	PyObject *coerced = NULL;
1432	PyObject *v1;
1433	PyObject *result;
1434
1435	if (!PyInstance_Check(v)) {
1436		Py_INCREF(Py_NotImplemented);
1437		return Py_NotImplemented;
1438	}
1439
1440	if (coerce_obj == NULL) {
1441		coerce_obj = PyString_InternFromString("__coerce__");
1442		if (coerce_obj == NULL)
1443			return NULL;
1444	}
1445	coercefunc = PyObject_GetAttr(v, coerce_obj);
1446	if (coercefunc == NULL) {
1447		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1448			return NULL;
1449		PyErr_Clear();
1450		return generic_binary_op(v, w, opname);
1451	}
1452
1453	args = PyTuple_Pack(1, w);
1454	if (args == NULL) {
1455		Py_DECREF(coercefunc);
1456		return NULL;
1457	}
1458	coerced = PyEval_CallObject(coercefunc, args);
1459	Py_DECREF(args);
1460	Py_DECREF(coercefunc);
1461	if (coerced == NULL) {
1462		return NULL;
1463	}
1464	if (coerced == Py_None || coerced == Py_NotImplemented) {
1465		Py_DECREF(coerced);
1466		return generic_binary_op(v, w, opname);
1467	}
1468	if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1469		Py_DECREF(coerced);
1470		PyErr_SetString(PyExc_TypeError,
1471				"coercion should return None or 2-tuple");
1472		return NULL;
1473	}
1474	v1 = PyTuple_GetItem(coerced, 0);
1475	w = PyTuple_GetItem(coerced, 1);
1476	if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
1477		/* prevent recursion if __coerce__ returns self as the first
1478		 * argument */
1479		result = generic_binary_op(v1, w, opname);
1480	} else {
1481		if (Py_EnterRecursiveCall(" after coercion"))
1482		    return NULL;
1483		if (swapped)
1484			result = (thisfunc)(w, v1);
1485		else
1486			result = (thisfunc)(v1, w);
1487		Py_LeaveRecursiveCall();
1488	}
1489	Py_DECREF(coerced);
1490	return result;
1491}
1492
1493/* Implement a binary operator involving at least one class instance. */
1494static PyObject *
1495do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
1496                   binaryfunc thisfunc)
1497{
1498	PyObject *result = half_binop(v, w, opname, thisfunc, 0);
1499	if (result == Py_NotImplemented) {
1500		Py_DECREF(result);
1501		result = half_binop(w, v, ropname, thisfunc, 1);
1502	}
1503	return result;
1504}
1505
1506static PyObject *
1507do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
1508			char *ropname, binaryfunc thisfunc)
1509{
1510	PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
1511	if (result == Py_NotImplemented) {
1512		Py_DECREF(result);
1513		result = do_binop(v, w, opname, ropname, thisfunc);
1514	}
1515	return result;
1516}
1517
1518static int
1519instance_coerce(PyObject **pv, PyObject **pw)
1520{
1521	PyObject *v = *pv;
1522	PyObject *w = *pw;
1523	PyObject *coercefunc;
1524	PyObject *args;
1525	PyObject *coerced;
1526
1527	if (coerce_obj == NULL) {
1528		coerce_obj = PyString_InternFromString("__coerce__");
1529		if (coerce_obj == NULL)
1530			return -1;
1531	}
1532	coercefunc = PyObject_GetAttr(v, coerce_obj);
1533	if (coercefunc == NULL) {
1534		/* No __coerce__ method */
1535		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1536			return -1;
1537		PyErr_Clear();
1538		return 1;
1539	}
1540	/* Has __coerce__ method: call it */
1541	args = PyTuple_Pack(1, w);
1542	if (args == NULL) {
1543		return -1;
1544	}
1545	coerced = PyEval_CallObject(coercefunc, args);
1546	Py_DECREF(args);
1547	Py_DECREF(coercefunc);
1548	if (coerced == NULL) {
1549		/* __coerce__ call raised an exception */
1550		return -1;
1551	}
1552	if (coerced == Py_None || coerced == Py_NotImplemented) {
1553		/* __coerce__ says "I can't do it" */
1554		Py_DECREF(coerced);
1555		return 1;
1556	}
1557	if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
1558		/* __coerce__ return value is malformed */
1559		Py_DECREF(coerced);
1560		PyErr_SetString(PyExc_TypeError,
1561			   "coercion should return None or 2-tuple");
1562		return -1;
1563	}
1564	/* __coerce__ returned two new values */
1565	*pv = PyTuple_GetItem(coerced, 0);
1566	*pw = PyTuple_GetItem(coerced, 1);
1567	Py_INCREF(*pv);
1568	Py_INCREF(*pw);
1569	Py_DECREF(coerced);
1570	return 0;
1571}
1572
1573#define UNARY(funcname, methodname) \
1574static PyObject *funcname(PyInstanceObject *self) { \
1575	static PyObject *o; \
1576	if (o == NULL) { o = PyString_InternFromString(methodname); \
1577			 if (o == NULL) return NULL; } \
1578	return generic_unary_op(self, o); \
1579}
1580
1581/* unary function with a fallback */
1582#define UNARY_FB(funcname, methodname, funcname_fb) \
1583static PyObject *funcname(PyInstanceObject *self) { \
1584	static PyObject *o; \
1585	if (o == NULL) { o = PyString_InternFromString(methodname); \
1586			 if (o == NULL) return NULL; } \
1587	if (PyObject_HasAttr((PyObject*)self, o)) \
1588		return generic_unary_op(self, o); \
1589	else \
1590		return funcname_fb(self); \
1591}
1592
1593#define BINARY(f, m, n) \
1594static PyObject *f(PyObject *v, PyObject *w) { \
1595	return do_binop(v, w, "__" m "__", "__r" m "__", n); \
1596}
1597
1598#define BINARY_INPLACE(f, m, n) \
1599static PyObject *f(PyObject *v, PyObject *w) { \
1600	return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
1601			"__r" m "__", n); \
1602}
1603
1604UNARY(instance_neg, "__neg__")
1605UNARY(instance_pos, "__pos__")
1606UNARY(instance_abs, "__abs__")
1607
1608BINARY(instance_or, "or", PyNumber_Or)
1609BINARY(instance_and, "and", PyNumber_And)
1610BINARY(instance_xor, "xor", PyNumber_Xor)
1611BINARY(instance_lshift, "lshift", PyNumber_Lshift)
1612BINARY(instance_rshift, "rshift", PyNumber_Rshift)
1613BINARY(instance_add, "add", PyNumber_Add)
1614BINARY(instance_sub, "sub", PyNumber_Subtract)
1615BINARY(instance_mul, "mul", PyNumber_Multiply)
1616BINARY(instance_div, "div", PyNumber_Divide)
1617BINARY(instance_mod, "mod", PyNumber_Remainder)
1618BINARY(instance_divmod, "divmod", PyNumber_Divmod)
1619BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide)
1620BINARY(instance_truediv, "truediv", PyNumber_TrueDivide)
1621
1622BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr)
1623BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor)
1624BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd)
1625BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift)
1626BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift)
1627BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd)
1628BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract)
1629BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply)
1630BINARY_INPLACE(instance_idiv, "div", PyNumber_InPlaceDivide)
1631BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder)
1632BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide)
1633BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
1634
1635/* Try a 3-way comparison, returning an int; v is an instance.  Return:
1636   -2 for an exception;
1637   -1 if v < w;
1638   0 if v == w;
1639   1 if v > w;
1640   2 if this particular 3-way comparison is not implemented or undefined.
1641*/
1642static int
1643half_cmp(PyObject *v, PyObject *w)
1644{
1645	static PyObject *cmp_obj;
1646	PyObject *args;
1647	PyObject *cmp_func;
1648	PyObject *result;
1649	long l;
1650
1651	assert(PyInstance_Check(v));
1652
1653	if (cmp_obj == NULL) {
1654		cmp_obj = PyString_InternFromString("__cmp__");
1655		if (cmp_obj == NULL)
1656			return -2;
1657	}
1658
1659	cmp_func = PyObject_GetAttr(v, cmp_obj);
1660	if (cmp_func == NULL) {
1661		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1662			return -2;
1663		PyErr_Clear();
1664		return 2;
1665	}
1666
1667	args = PyTuple_Pack(1, w);
1668	if (args == NULL) {
1669		Py_DECREF(cmp_func);
1670		return -2;
1671	}
1672
1673	result = PyEval_CallObject(cmp_func, args);
1674	Py_DECREF(args);
1675	Py_DECREF(cmp_func);
1676
1677	if (result == NULL)
1678		return -2;
1679
1680	if (result == Py_NotImplemented) {
1681		Py_DECREF(result);
1682		return 2;
1683	}
1684
1685	l = PyInt_AsLong(result);
1686	Py_DECREF(result);
1687	if (l == -1 && PyErr_Occurred()) {
1688		PyErr_SetString(PyExc_TypeError,
1689			     "comparison did not return an int");
1690		return -2;
1691	}
1692
1693	return l < 0 ? -1 : l > 0 ? 1 : 0;
1694}
1695
1696/* Try a 3-way comparison, returning an int; either v or w is an instance.
1697   We first try a coercion.  Return:
1698   -2 for an exception;
1699   -1 if v < w;
1700   0 if v == w;
1701   1 if v > w;
1702   2 if this particular 3-way comparison is not implemented or undefined.
1703   THIS IS ONLY CALLED FROM object.c!
1704*/
1705static int
1706instance_compare(PyObject *v, PyObject *w)
1707{
1708	int c;
1709
1710	c = PyNumber_CoerceEx(&v, &w);
1711	if (c < 0)
1712		return -2;
1713	if (c == 0) {
1714		/* If neither is now an instance, use regular comparison */
1715		if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
1716			c = PyObject_Compare(v, w);
1717			Py_DECREF(v);
1718			Py_DECREF(w);
1719			if (PyErr_Occurred())
1720				return -2;
1721			return c < 0 ? -1 : c > 0 ? 1 : 0;
1722		}
1723	}
1724	else {
1725		/* The coercion didn't do anything.
1726		   Treat this the same as returning v and w unchanged. */
1727		Py_INCREF(v);
1728		Py_INCREF(w);
1729	}
1730
1731	if (PyInstance_Check(v)) {
1732		c = half_cmp(v, w);
1733		if (c <= 1) {
1734			Py_DECREF(v);
1735			Py_DECREF(w);
1736			return c;
1737		}
1738	}
1739	if (PyInstance_Check(w)) {
1740		c = half_cmp(w, v);
1741		if (c <= 1) {
1742			Py_DECREF(v);
1743			Py_DECREF(w);
1744			if (c >= -1)
1745				c = -c;
1746			return c;
1747		}
1748	}
1749	Py_DECREF(v);
1750	Py_DECREF(w);
1751	return 2;
1752}
1753
1754static int
1755instance_nonzero(PyInstanceObject *self)
1756{
1757	PyObject *func, *res;
1758	long outcome;
1759	static PyObject *nonzerostr;
1760
1761	if (nonzerostr == NULL) {
1762		nonzerostr = PyString_InternFromString("__nonzero__");
1763		if (nonzerostr == NULL)
1764			return -1;
1765	}
1766	if ((func = instance_getattr(self, nonzerostr)) == NULL) {
1767		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1768			return -1;
1769		PyErr_Clear();
1770		if (lenstr == NULL) {
1771			lenstr = PyString_InternFromString("__len__");
1772			if (lenstr == NULL)
1773				return -1;
1774		}
1775		if ((func = instance_getattr(self, lenstr)) == NULL) {
1776			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1777				return -1;
1778			PyErr_Clear();
1779			/* Fall back to the default behavior:
1780			   all instances are nonzero */
1781			return 1;
1782		}
1783	}
1784	res = PyEval_CallObject(func, (PyObject *)NULL);
1785	Py_DECREF(func);
1786	if (res == NULL)
1787		return -1;
1788	if (!PyInt_Check(res)) {
1789		Py_DECREF(res);
1790		PyErr_SetString(PyExc_TypeError,
1791				"__nonzero__ should return an int");
1792		return -1;
1793	}
1794	outcome = PyInt_AsLong(res);
1795	Py_DECREF(res);
1796	if (outcome < 0) {
1797		PyErr_SetString(PyExc_ValueError,
1798				"__nonzero__ should return >= 0");
1799		return -1;
1800	}
1801	return outcome > 0;
1802}
1803
1804static PyObject *
1805instance_index(PyInstanceObject *self)
1806{
1807	PyObject *func, *res;
1808	static PyObject *indexstr = NULL;
1809
1810	if (indexstr == NULL) {
1811		indexstr = PyString_InternFromString("__index__");
1812		if (indexstr == NULL)
1813			return NULL;
1814	}	
1815	if ((func = instance_getattr(self, indexstr)) == NULL) {
1816		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1817			return NULL;
1818		PyErr_Clear();
1819		PyErr_SetString(PyExc_TypeError, 
1820				"object cannot be interpreted as an index");
1821		return NULL;
1822	}
1823	res = PyEval_CallObject(func, (PyObject *)NULL);
1824	Py_DECREF(func);
1825	return res;
1826}
1827
1828
1829UNARY(instance_invert, "__invert__")
1830UNARY(_instance_trunc, "__trunc__")
1831
1832static PyObject *
1833instance_int(PyInstanceObject *self)
1834{
1835	PyObject *truncated;
1836	static PyObject *int_name;
1837	if (int_name == NULL) {
1838		int_name = PyString_InternFromString("__int__");
1839		if (int_name == NULL)
1840			return NULL;
1841	}
1842	if (PyObject_HasAttr((PyObject*)self, int_name))
1843		return generic_unary_op(self, int_name);
1844
1845	truncated = _instance_trunc(self);
1846	/* __trunc__ is specified to return an Integral type, but
1847	   int() needs to return an int. */
1848	return _PyNumber_ConvertIntegralToInt(
1849		truncated,
1850		"__trunc__ returned non-Integral (type %.200s)");
1851}
1852
1853UNARY_FB(instance_long, "__long__", instance_int)
1854UNARY(instance_float, "__float__")
1855UNARY(instance_oct, "__oct__")
1856UNARY(instance_hex, "__hex__")
1857
1858static PyObject *
1859bin_power(PyObject *v, PyObject *w)
1860{
1861	return PyNumber_Power(v, w, Py_None);
1862}
1863
1864/* This version is for ternary calls only (z != None) */
1865static PyObject *
1866instance_pow(PyObject *v, PyObject *w, PyObject *z)
1867{
1868	if (z == Py_None) {
1869		return do_binop(v, w, "__pow__", "__rpow__", bin_power);
1870	}
1871	else {
1872		PyObject *func;
1873		PyObject *args;
1874		PyObject *result;
1875
1876		/* XXX Doesn't do coercions... */
1877		func = PyObject_GetAttrString(v, "__pow__");
1878		if (func == NULL)
1879			return NULL;
1880		args = PyTuple_Pack(2, w, z);
1881		if (args == NULL) {
1882			Py_DECREF(func);
1883			return NULL;
1884		}
1885		result = PyEval_CallObject(func, args);
1886		Py_DECREF(func);
1887		Py_DECREF(args);
1888		return result;
1889	}
1890}
1891
1892static PyObject *
1893bin_inplace_power(PyObject *v, PyObject *w)
1894{
1895	return PyNumber_InPlacePower(v, w, Py_None);
1896}
1897
1898
1899static PyObject *
1900instance_ipow(PyObject *v, PyObject *w, PyObject *z)
1901{
1902	if (z == Py_None) {
1903		return do_binop_inplace(v, w, "__ipow__", "__pow__",
1904			"__rpow__", bin_inplace_power);
1905	}
1906	else {
1907		/* XXX Doesn't do coercions... */
1908		PyObject *func;
1909		PyObject *args;
1910		PyObject *result;
1911
1912		func = PyObject_GetAttrString(v, "__ipow__");
1913		if (func == NULL) {
1914			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1915				return NULL;
1916			PyErr_Clear();
1917			return instance_pow(v, w, z);
1918		}
1919		args = PyTuple_Pack(2, w, z);
1920		if (args == NULL) {
1921			Py_DECREF(func);
1922			return NULL;
1923		}
1924		result = PyEval_CallObject(func, args);
1925		Py_DECREF(func);
1926		Py_DECREF(args);
1927		return result;
1928	}
1929}
1930
1931
1932/* Map rich comparison operators to their __xx__ namesakes */
1933#define NAME_OPS 6
1934static PyObject **name_op = NULL;
1935
1936static int
1937init_name_op(void)
1938{
1939	int i;
1940	char *_name_op[] = {
1941		"__lt__",
1942		"__le__",
1943		"__eq__",
1944		"__ne__",
1945		"__gt__",
1946		"__ge__",
1947	};
1948
1949	name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
1950	if (name_op == NULL)
1951		return -1;
1952	for (i = 0; i < NAME_OPS; ++i) {
1953		name_op[i] = PyString_InternFromString(_name_op[i]);
1954		if (name_op[i] == NULL)
1955			return -1;
1956	}
1957	return 0;
1958}
1959
1960static PyObject *
1961half_richcompare(PyObject *v, PyObject *w, int op)
1962{
1963	PyObject *method;
1964	PyObject *args;
1965	PyObject *res;
1966
1967	assert(PyInstance_Check(v));
1968
1969	if (name_op == NULL) {
1970		if (init_name_op() < 0)
1971			return NULL;
1972	}
1973	/* If the instance doesn't define an __getattr__ method, use
1974	   instance_getattr2 directly because it will not set an
1975	   exception on failure. */
1976	if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
1977		method = instance_getattr2((PyInstanceObject *)v,
1978					   name_op[op]);
1979	else
1980		method = PyObject_GetAttr(v, name_op[op]);
1981	if (method == NULL) {
1982		if (PyErr_Occurred()) {
1983			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
1984				return NULL;
1985			PyErr_Clear();
1986		}
1987		res = Py_NotImplemented;
1988		Py_INCREF(res);
1989		return res;
1990	}
1991
1992	args = PyTuple_Pack(1, w);
1993	if (args == NULL) {
1994		Py_DECREF(method);
1995		return NULL;
1996	}
1997
1998	res = PyEval_CallObject(method, args);
1999	Py_DECREF(args);
2000	Py_DECREF(method);
2001
2002	return res;
2003}
2004
2005static PyObject *
2006instance_richcompare(PyObject *v, PyObject *w, int op)
2007{
2008	PyObject *res;
2009
2010	if (PyInstance_Check(v)) {
2011		res = half_richcompare(v, w, op);
2012		if (res != Py_NotImplemented)
2013			return res;
2014		Py_DECREF(res);
2015	}
2016
2017	if (PyInstance_Check(w)) {
2018		res = half_richcompare(w, v, _Py_SwappedOp[op]);
2019		if (res != Py_NotImplemented)
2020			return res;
2021		Py_DECREF(res);
2022	}
2023
2024	Py_INCREF(Py_NotImplemented);
2025	return Py_NotImplemented;
2026}
2027
2028
2029/* Get the iterator */
2030static PyObject *
2031instance_getiter(PyInstanceObject *self)
2032{
2033	PyObject *func;
2034
2035	if (iterstr == NULL) {
2036		iterstr = PyString_InternFromString("__iter__");
2037		if (iterstr == NULL)
2038			return NULL;
2039	}
2040	if (getitemstr == NULL) {
2041		getitemstr = PyString_InternFromString("__getitem__");
2042		if (getitemstr == NULL)
2043			return NULL;
2044	}
2045
2046	if ((func = instance_getattr(self, iterstr)) != NULL) {
2047		PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2048		Py_DECREF(func);
2049		if (res != NULL && !PyIter_Check(res)) {
2050			PyErr_Format(PyExc_TypeError,
2051				     "__iter__ returned non-iterator "
2052				     "of type '%.100s'",
2053				     res->ob_type->tp_name);
2054			Py_DECREF(res);
2055			res = NULL;
2056		}
2057		return res;
2058	}
2059	if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2060		return NULL;
2061	PyErr_Clear();
2062	if ((func = instance_getattr(self, getitemstr)) == NULL) {
2063		PyErr_SetString(PyExc_TypeError,
2064				"iteration over non-sequence");
2065		return NULL;
2066	}
2067	Py_DECREF(func);
2068	return PySeqIter_New((PyObject *)self);
2069}
2070
2071
2072/* Call the iterator's next */
2073static PyObject *
2074instance_iternext(PyInstanceObject *self)
2075{
2076	PyObject *func;
2077
2078	if (nextstr == NULL) {
2079		nextstr = PyString_InternFromString("next");
2080		if (nextstr == NULL)
2081			return NULL;
2082	}
2083
2084	if ((func = instance_getattr(self, nextstr)) != NULL) {
2085		PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
2086		Py_DECREF(func);
2087		if (res != NULL) {
2088			return res;
2089		}
2090		if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
2091			PyErr_Clear();
2092			return NULL;
2093		}
2094		return NULL;
2095	}
2096	PyErr_SetString(PyExc_TypeError, "instance has no next() method");
2097	return NULL;
2098}
2099
2100static PyObject *
2101instance_call(PyObject *func, PyObject *arg, PyObject *kw)
2102{
2103	PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
2104	if (call == NULL) {
2105		PyInstanceObject *inst = (PyInstanceOb

Large files files are truncated, but you can click here to view the full file