descrobject.c 30.9 KB
Newer Older
1 2 3 4 5 6 7 8
/* Descriptors -- a new, flexible way to describe attributes */

#include "Python.h"
#include "structmember.h" /* Why is this not included in Python.h? */

static void
descr_dealloc(PyDescrObject *descr)
{
9
	_PyObject_GC_UNTRACK(descr);
10 11
	Py_XDECREF(descr->d_type);
	Py_XDECREF(descr->d_name);
12
	PyObject_GC_Del(descr);
13 14
}

15
static PyObject *
16 17
descr_name(PyDescrObject *descr)
{
18
	if (descr->d_name != NULL && PyUnicode_Check(descr->d_name))
19 20
		return descr->d_name;
	return NULL;
21 22 23 24 25
}

static PyObject *
descr_repr(PyDescrObject *descr, char *format)
{
26 27 28 29 30
	PyObject *name = NULL;
	if (descr->d_name != NULL && PyUnicode_Check(descr->d_name))
		name = descr->d_name;

	return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name);
31 32 33 34 35
}

static PyObject *
method_repr(PyMethodDescrObject *descr)
{
36
	return descr_repr((PyDescrObject *)descr,
37
			  "<method '%V' of '%s' objects>");
38 39 40 41 42
}

static PyObject *
member_repr(PyMemberDescrObject *descr)
{
43
	return descr_repr((PyDescrObject *)descr,
44
			  "<member '%V' of '%s' objects>");
45 46 47 48 49
}

static PyObject *
getset_repr(PyGetSetDescrObject *descr)
{
50
	return descr_repr((PyDescrObject *)descr,
51
			  "<attribute '%V' of '%s' objects>");
52 53 54
}

static PyObject *
55
wrapperdescr_repr(PyWrapperDescrObject *descr)
56
{
57
	return descr_repr((PyDescrObject *)descr,
58
			  "<slot wrapper '%V' of '%s' objects>");
59 60 61
}

static int
62
descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres)
63
{
64
	if (obj == NULL) {
65 66 67 68
		Py_INCREF(descr);
		*pres = (PyObject *)descr;
		return 1;
	}
69
	if (!PyObject_TypeCheck(obj, descr->d_type)) {
70
		PyErr_Format(PyExc_TypeError,
71
			     "descriptor '%V' for '%s' objects "
72
			     "doesn't apply to '%s' object",
73
			     descr_name((PyDescrObject *)descr), "?",
74 75 76 77 78 79 80 81
			     descr->d_type->tp_name,
			     obj->ob_type->tp_name);
		*pres = NULL;
		return 1;
	}
	return 0;
}

82
static PyObject *
83
classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type)
84
{
85 86 87 88 89 90 91
	/* Ensure a valid type.  Class methods ignore obj. */
	if (type == NULL) {
		if (obj != NULL)
			type = (PyObject *)obj->ob_type;
		else {
			/* Wot - no type?! */
			PyErr_Format(PyExc_TypeError,
92
				     "descriptor '%V' for type '%s' "
93
				     "needs either an object or a type",
94
				     descr_name((PyDescrObject *)descr), "?",
95 96 97 98 99 100
				     descr->d_type->tp_name);
			return NULL;
		}
	}
	if (!PyType_Check(type)) {
		PyErr_Format(PyExc_TypeError,
101
			     "descriptor '%V' for type '%s' "
102
			     "needs a type, not a '%s' as arg 2",
103
			     descr_name((PyDescrObject *)descr), "?",
104 105 106 107 108 109
			     descr->d_type->tp_name,
			     type->ob_type->tp_name);
		return NULL;
	}
	if (!PyType_IsSubtype((PyTypeObject *)type, descr->d_type)) {
		PyErr_Format(PyExc_TypeError,
110
			     "descriptor '%V' for type '%s' "
111
			     "doesn't apply to type '%s'",
112
			     descr_name((PyDescrObject *)descr), "?",
113 114 115 116 117
			     descr->d_type->tp_name,
			     ((PyTypeObject *)type)->tp_name);
		return NULL;
	}
	return PyCFunction_New(descr->d_method, type);
118 119
}

120
static PyObject *
121
method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type)
122 123 124
{
	PyObject *res;

125
	if (descr_check((PyDescrObject *)descr, obj, &res))
126 127 128 129 130
		return res;
	return PyCFunction_New(descr->d_method, obj);
}

static PyObject *
131
member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type)
132 133 134
{
	PyObject *res;

135
	if (descr_check((PyDescrObject *)descr, obj, &res))
136
		return res;
137
	return PyMember_GetOne((char *)obj, descr->d_member);
138 139 140
}

static PyObject *
141
getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type)
142 143 144
{
	PyObject *res;

145
	if (descr_check((PyDescrObject *)descr, obj, &res))
146 147 148
		return res;
	if (descr->d_getset->get != NULL)
		return descr->d_getset->get(obj, descr->d_getset->closure);
149
	PyErr_Format(PyExc_AttributeError,
150 151
		     "attribute '%V' of '%.100s' objects is not readable",
		     descr_name((PyDescrObject *)descr), "?",
152 153 154 155 156
		     descr->d_type->tp_name);
	return NULL;
}

static PyObject *
157
wrapperdescr_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type)
158 159 160
{
	PyObject *res;

161
	if (descr_check((PyDescrObject *)descr, obj, &res))
162 163 164 165 166 167 168 169 170 171 172
		return res;
	return PyWrapper_New((PyObject *)descr, obj);
}

static int
descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value,
	       int *pres)
{
	assert(obj != NULL);
	if (!PyObject_IsInstance(obj, (PyObject *)(descr->d_type))) {
		PyErr_Format(PyExc_TypeError,
173
			     "descriptor '%V' for '%.100s' objects "
174
			     "doesn't apply to '%.100s' object",
175
			     descr_name(descr), "?",
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
			     descr->d_type->tp_name,
			     obj->ob_type->tp_name);
		*pres = -1;
		return 1;
	}
	return 0;
}

static int
member_set(PyMemberDescrObject *descr, PyObject *obj, PyObject *value)
{
	int res;

	if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
		return res;
191
	return PyMember_SetOne((char *)obj, descr->d_member, value);
192 193 194 195 196 197 198 199 200 201 202 203
}

static int
getset_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value)
{
	int res;

	if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
		return res;
	if (descr->d_getset->set != NULL)
		return descr->d_getset->set(obj, value,
					    descr->d_getset->closure);
204
	PyErr_Format(PyExc_AttributeError,
205 206
		     "attribute '%V' of '%.100s' objects is not writable",
		     descr_name((PyDescrObject *)descr), "?",
207 208 209 210 211 212 213
		     descr->d_type->tp_name);
	return -1;
}

static PyObject *
methoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwds)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
214
	Py_ssize_t argc;
215 216 217 218 219 220 221
	PyObject *self, *func, *result;

	/* Make sure that the first argument is acceptable as 'self' */
	assert(PyTuple_Check(args));
	argc = PyTuple_GET_SIZE(args);
	if (argc < 1) {
		PyErr_Format(PyExc_TypeError,
222
			     "descriptor '%V' of '%.100s' "
223
			     "object needs an argument",
224
			     descr_name((PyDescrObject *)descr), "?",
225 226 227 228 229 230
			     descr->d_type->tp_name);
		return NULL;
	}
	self = PyTuple_GET_ITEM(args, 0);
	if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
		PyErr_Format(PyExc_TypeError,
231
			     "descriptor '%V' "
232 233
			     "requires a '%.100s' object "
			     "but received a '%.100s'",
234
			     descr_name((PyDescrObject *)descr), "?",
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
			     descr->d_type->tp_name,
			     self->ob_type->tp_name);
		return NULL;
	}

	func = PyCFunction_New(descr->d_method, self);
	if (func == NULL)
		return NULL;
	args = PyTuple_GetSlice(args, 1, argc);
	if (args == NULL) {
		Py_DECREF(func);
		return NULL;
	}
	result = PyEval_CallObjectWithKeywords(func, args, kwds);
	Py_DECREF(args);
	Py_DECREF(func);
	return result;
}

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
static PyObject *
classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args,
		      PyObject *kwds)
{
	PyObject *func, *result;

	func = PyCFunction_New(descr->d_method, (PyObject *)descr->d_type);
	if (func == NULL)
		return NULL;

	result = PyEval_CallObjectWithKeywords(func, args, kwds);
	Py_DECREF(func);
	return result;
}

269 270 271
static PyObject *
wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
272
	Py_ssize_t argc;
273 274 275 276 277 278 279
	PyObject *self, *func, *result;

	/* Make sure that the first argument is acceptable as 'self' */
	assert(PyTuple_Check(args));
	argc = PyTuple_GET_SIZE(args);
	if (argc < 1) {
		PyErr_Format(PyExc_TypeError,
280
			     "descriptor '%V' of '%.100s' "
281
			     "object needs an argument",
282
			     descr_name((PyDescrObject *)descr), "?",
283 284 285 286 287 288
			     descr->d_type->tp_name);
		return NULL;
	}
	self = PyTuple_GET_ITEM(args, 0);
	if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
		PyErr_Format(PyExc_TypeError,
289
			     "descriptor '%V' "
290 291
			     "requires a '%.100s' object "
			     "but received a '%.100s'",
292
			     descr_name((PyDescrObject *)descr), "?",
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
			     descr->d_type->tp_name,
			     self->ob_type->tp_name);
		return NULL;
	}

	func = PyWrapper_New((PyObject *)descr, self);
	if (func == NULL)
		return NULL;
	args = PyTuple_GetSlice(args, 1, argc);
	if (args == NULL) {
		Py_DECREF(func);
		return NULL;
	}
	result = PyEval_CallObjectWithKeywords(func, args, kwds);
	Py_DECREF(args);
	Py_DECREF(func);
	return result;
}

static PyObject *
313
method_get_doc(PyMethodDescrObject *descr, void *closure)
314 315 316 317 318
{
	if (descr->d_method->ml_doc == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
Neal Norwitz's avatar
Neal Norwitz committed
319
	return PyUnicode_FromString(descr->d_method->ml_doc);
320 321
}

322
static PyMemberDef descr_members[] = {
323 324 325 326 327
	{"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY},
	{"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY},
	{0}
};

328
static PyGetSetDef method_getset[] = {
329 330 331 332 333 334 335 336 337 338 339
	{"__doc__", (getter)method_get_doc},
	{0}
};

static PyObject *
member_get_doc(PyMemberDescrObject *descr, void *closure)
{
	if (descr->d_member->doc == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
Neal Norwitz's avatar
Neal Norwitz committed
340
	return PyUnicode_FromString(descr->d_member->doc);
341 342
}

343
static PyGetSetDef member_getset[] = {
344 345 346 347
	{"__doc__", (getter)member_get_doc},
	{0}
};

348 349 350 351 352 353 354
static PyObject *
getset_get_doc(PyGetSetDescrObject *descr, void *closure)
{
	if (descr->d_getset->doc == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
Neal Norwitz's avatar
Neal Norwitz committed
355
	return PyUnicode_FromString(descr->d_getset->doc);
356 357 358 359 360 361 362
}

static PyGetSetDef getset_getset[] = {
	{"__doc__", (getter)getset_get_doc},
	{0}
};

363
static PyObject *
364
wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure)
365 366 367 368 369
{
	if (descr->d_base->doc == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
Neal Norwitz's avatar
Neal Norwitz committed
370
	return PyUnicode_FromString(descr->d_base->doc);
371 372
}

373 374
static PyGetSetDef wrapperdescr_getset[] = {
	{"__doc__", (getter)wrapperdescr_get_doc},
375 376 377
	{0}
};

378 379 380 381
static int
descr_traverse(PyObject *self, visitproc visit, void *arg)
{
	PyDescrObject *descr = (PyDescrObject *)self;
382
	Py_VISIT(descr->d_type);
383 384 385
	return 0;
}

386
static PyTypeObject PyMethodDescr_Type = {
387
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
	"method_descriptor",
	sizeof(PyMethodDescrObject),
	0,
	(destructor)descr_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)method_repr,			/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	(ternaryfunc)methoddescr_call,		/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
406
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
407
	0,					/* tp_doc */
408
	descr_traverse,				/* tp_traverse */
409 410 411 412 413 414 415
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	descr_members,				/* tp_members */
416
	method_getset,				/* tp_getset */
417 418 419 420 421 422
	0,					/* tp_base */
	0,					/* tp_dict */
	(descrgetfunc)method_get,		/* tp_descr_get */
	0,					/* tp_descr_set */
};

423
/* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */
424
static PyTypeObject PyClassMethodDescr_Type = {
425
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
426
	"classmethod_descriptor",
427 428 429 430 431 432 433 434 435 436 437 438
	sizeof(PyMethodDescrObject),
	0,
	(destructor)descr_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)method_repr,			/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
439
	(ternaryfunc)classmethoddescr_call,	/* tp_call */
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
	0,					/* tp_doc */
	descr_traverse,				/* tp_traverse */
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	descr_members,				/* tp_members */
	method_getset,				/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	(descrgetfunc)classmethod_get,		/* tp_descr_get */
	0,					/* tp_descr_set */
};

461
static PyTypeObject PyMemberDescr_Type = {
462
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
463 464 465 466 467 468 469 470 471 472 473 474 475
	"member_descriptor",
	sizeof(PyMemberDescrObject),
	0,
	(destructor)descr_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)member_repr,			/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
476
	0,					/* tp_call */
477 478 479 480
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
481
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
482
	0,					/* tp_doc */
483
	descr_traverse,				/* tp_traverse */
484 485 486 487 488 489 490
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	descr_members,				/* tp_members */
491
	member_getset,				/* tp_getset */
492 493 494 495 496 497 498
	0,					/* tp_base */
	0,					/* tp_dict */
	(descrgetfunc)member_get,		/* tp_descr_get */
	(descrsetfunc)member_set,		/* tp_descr_set */
};

static PyTypeObject PyGetSetDescr_Type = {
499
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
500 501 502 503 504 505 506 507 508 509 510 511 512
	"getset_descriptor",
	sizeof(PyGetSetDescrObject),
	0,
	(destructor)descr_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)getset_repr,			/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
513
	0,					/* tp_call */
514 515 516 517
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
518
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
519
	0,					/* tp_doc */
520
	descr_traverse,				/* tp_traverse */
521 522 523 524 525 526 527
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	descr_members,				/* tp_members */
528
	getset_getset,				/* tp_getset */
529 530 531 532 533 534
	0,					/* tp_base */
	0,					/* tp_dict */
	(descrgetfunc)getset_get,		/* tp_descr_get */
	(descrsetfunc)getset_set,		/* tp_descr_set */
};

535
PyTypeObject PyWrapperDescr_Type = {
536
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
537 538 539 540 541 542 543 544
	"wrapper_descriptor",
	sizeof(PyWrapperDescrObject),
	0,
	(destructor)descr_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
545
	(reprfunc)wrapperdescr_repr,		/* tp_repr */
546 547 548 549 550 551 552 553 554
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	(ternaryfunc)wrapperdescr_call,		/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
555
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
556
	0,					/* tp_doc */
557
	descr_traverse,				/* tp_traverse */
558 559 560 561 562 563 564
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
	descr_members,				/* tp_members */
565
	wrapperdescr_getset,			/* tp_getset */
566 567
	0,					/* tp_base */
	0,					/* tp_dict */
568
	(descrgetfunc)wrapperdescr_get,		/* tp_descr_get */
569 570 571 572
	0,					/* tp_descr_set */
};

static PyDescrObject *
573
descr_new(PyTypeObject *descrtype, PyTypeObject *type, const char *name)
574 575 576 577 578 579 580
{
	PyDescrObject *descr;

	descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0);
	if (descr != NULL) {
		Py_XINCREF(type);
		descr->d_type = type;
581
		descr->d_name = PyUnicode_InternFromString(name);
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
		if (descr->d_name == NULL) {
			Py_DECREF(descr);
			descr = NULL;
		}
	}
	return descr;
}

PyObject *
PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method)
{
	PyMethodDescrObject *descr;

	descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type,
						 type, method->ml_name);
	if (descr != NULL)
		descr->d_method = method;
	return (PyObject *)descr;
}

602 603 604 605 606 607 608 609 610 611 612 613
PyObject *
PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
{
	PyMethodDescrObject *descr;

	descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type,
						 type, method->ml_name);
	if (descr != NULL)
		descr->d_method = method;
	return (PyObject *)descr;
}

614
PyObject *
615
PyDescr_NewMember(PyTypeObject *type, PyMemberDef *member)
616 617 618 619 620 621 622 623 624 625 626
{
	PyMemberDescrObject *descr;

	descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type,
						 type, member->name);
	if (descr != NULL)
		descr->d_member = member;
	return (PyObject *)descr;
}

PyObject *
627
PyDescr_NewGetSet(PyTypeObject *type, PyGetSetDef *getset)
628 629 630 631 632 633 634 635 636 637 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
{
	PyGetSetDescrObject *descr;

	descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type,
						 type, getset->name);
	if (descr != NULL)
		descr->d_getset = getset;
	return (PyObject *)descr;
}

PyObject *
PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped)
{
	PyWrapperDescrObject *descr;

	descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type,
						 type, base->name);
	if (descr != NULL) {
		descr->d_base = base;
		descr->d_wrapped = wrapped;
	}
	return (PyObject *)descr;
}


/* --- Readonly proxy for dictionaries (actually any mapping) --- */

/* This has no reason to be in this file except that adding new files is a
   bit of a pain */

typedef struct {
	PyObject_HEAD
	PyObject *dict;
} proxyobject;

Martin v. Löwis's avatar
Martin v. Löwis committed
663
static Py_ssize_t
664 665 666 667 668 669 670 671 672 673 674 675
proxy_len(proxyobject *pp)
{
	return PyObject_Size(pp->dict);
}

static PyObject *
proxy_getitem(proxyobject *pp, PyObject *key)
{
	return PyObject_GetItem(pp->dict, key);
}

static PyMappingMethods proxy_as_mapping = {
Martin v. Löwis's avatar
Martin v. Löwis committed
676
	(lenfunc)proxy_len,			/* mp_length */
677 678 679 680 681 682 683
	(binaryfunc)proxy_getitem,		/* mp_subscript */
	0,					/* mp_ass_subscript */
};

static int
proxy_contains(proxyobject *pp, PyObject *key)
{
684
	return PyDict_Contains(pp->dict, key);
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
}

static PySequenceMethods proxy_as_sequence = {
	0,					/* sq_length */
	0,					/* sq_concat */
	0,					/* sq_repeat */
	0,					/* sq_item */
	0,					/* sq_slice */
	0,					/* sq_ass_item */
	0,					/* sq_ass_slice */
	(objobjproc)proxy_contains,		/* sq_contains */
	0,					/* sq_inplace_concat */
	0,					/* sq_inplace_repeat */
};

static PyObject *
proxy_get(proxyobject *pp, PyObject *args)
{
	PyObject *key, *def = Py_None;

705
	if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def))
706 707 708 709 710
		return NULL;
	return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def);
}

static PyObject *
711
proxy_keys(proxyobject *pp)
712 713 714 715 716
{
	return PyMapping_Keys(pp->dict);
}

static PyObject *
717
proxy_values(proxyobject *pp)
718 719 720 721 722
{
	return PyMapping_Values(pp->dict);
}

static PyObject *
723
proxy_items(proxyobject *pp)
724 725 726 727
{
	return PyMapping_Items(pp->dict);
}

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
static PyObject *
proxy_iterkeys(proxyobject *pp)
{
	return PyObject_CallMethod(pp->dict, "iterkeys", NULL);
}

static PyObject *
proxy_itervalues(proxyobject *pp)
{
	return PyObject_CallMethod(pp->dict, "itervalues", NULL);
}

static PyObject *
proxy_iteritems(proxyobject *pp)
{
	return PyObject_CallMethod(pp->dict, "iteritems", NULL);
}
745
static PyObject *
746
proxy_copy(proxyobject *pp)
747 748 749 750 751
{
	return PyObject_CallMethod(pp->dict, "copy", NULL);
}

static PyMethodDef proxy_methods[] = {
752
	{"get",       (PyCFunction)proxy_get,        METH_VARARGS,
753
	 PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d."
754
	 				"  d defaults to None.")},
755
	{"keys",      (PyCFunction)proxy_keys,       METH_NOARGS,
756
	 PyDoc_STR("D.keys() -> list of D's keys")},
757
	{"values",    (PyCFunction)proxy_values,     METH_NOARGS,
758
	 PyDoc_STR("D.values() -> list of D's values")},
759
	{"items",     (PyCFunction)proxy_items,      METH_NOARGS,
760
	 PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")},
761
	{"iterkeys",  (PyCFunction)proxy_iterkeys,   METH_NOARGS,
762
	 PyDoc_STR("D.iterkeys() -> an iterator over the keys of D")},
763
	{"itervalues",(PyCFunction)proxy_itervalues, METH_NOARGS,
764
	 PyDoc_STR("D.itervalues() -> an iterator over the values of D")},
765
	{"iteritems", (PyCFunction)proxy_iteritems,  METH_NOARGS,
766 767
	 PyDoc_STR("D.iteritems() ->"
	 	   " an iterator over the (key, value) items of D")},
768
	{"copy",      (PyCFunction)proxy_copy,       METH_NOARGS,
769
	 PyDoc_STR("D.copy() -> a shallow copy of D")},
770 771 772 773 774 775
	{0}
};

static void
proxy_dealloc(proxyobject *pp)
{
776
	_PyObject_GC_UNTRACK(pp);
777
	Py_DECREF(pp->dict);
778
	PyObject_GC_Del(pp);
779 780 781 782 783 784 785 786
}

static PyObject *
proxy_getiter(proxyobject *pp)
{
	return PyObject_GetIter(pp->dict);
}

787
static PyObject *
788 789 790 791 792
proxy_str(proxyobject *pp)
{
	return PyObject_Str(pp->dict);
}

793 794 795 796
static int
proxy_traverse(PyObject *self, visitproc visit, void *arg)
{
	proxyobject *pp = (proxyobject *)self;
797
	Py_VISIT(pp->dict);
798 799 800
	return 0;
}

801 802 803 804 805 806 807 808 809 810 811 812
static int
proxy_compare(proxyobject *v, PyObject *w)
{
	return PyObject_Compare(v->dict, w);
}

static PyObject *
proxy_richcompare(proxyobject *v, PyObject *w, int op)
{
	return PyObject_RichCompare(v->dict, w, op);
}

813
static PyTypeObject proxytype = {
814
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
815
	"dictproxy",				/* tp_name */
816 817 818 819 820 821 822
	sizeof(proxyobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	(destructor)proxy_dealloc, 		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
823
	(cmpfunc)proxy_compare,			/* tp_compare */
824 825 826 827 828 829 830 831 832 833
	0,					/* tp_repr */
	0,					/* tp_as_number */
	&proxy_as_sequence,			/* tp_as_sequence */
	&proxy_as_mapping,			/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	(reprfunc)proxy_str,			/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
834
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
835
 	0,					/* tp_doc */
836
	proxy_traverse,				/* tp_traverse */
837
 	0,					/* tp_clear */
838
	(richcmpfunc)proxy_richcompare,		/* tp_richcompare */
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
	0,					/* tp_weaklistoffset */
	(getiterfunc)proxy_getiter,		/* tp_iter */
	0,					/* tp_iternext */
	proxy_methods,				/* tp_methods */
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
};

PyObject *
PyDictProxy_New(PyObject *dict)
{
	proxyobject *pp;

856
	pp = PyObject_GC_New(proxyobject, &proxytype);
857 858 859
	if (pp != NULL) {
		Py_INCREF(dict);
		pp->dict = dict;
860
		_PyObject_GC_TRACK(pp);
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
	}
	return (PyObject *)pp;
}


/* --- Wrapper object for "slot" methods --- */

/* This has no reason to be in this file except that adding new files is a
   bit of a pain */

typedef struct {
	PyObject_HEAD
	PyWrapperDescrObject *descr;
	PyObject *self;
} wrapperobject;

static void
wrapper_dealloc(wrapperobject *wp)
{
880 881
	PyObject_GC_UnTrack(wp);
	Py_TRASHCAN_SAFE_BEGIN(wp)
882 883
	Py_XDECREF(wp->descr);
	Py_XDECREF(wp->self);
884
	PyObject_GC_Del(wp);
885
	Py_TRASHCAN_SAFE_END(wp)
886 887
}

888 889 890
static int
wrapper_compare(wrapperobject *a, wrapperobject *b)
{
891 892
	if (a->descr == b->descr)
		return PyObject_Compare(a->self, b->self);
893 894 895 896
	else
		return (a->descr < b->descr) ? -1 : 1;
}

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
static long
wrapper_hash(wrapperobject *wp)
{
	int x, y;
	x = _Py_HashPointer(wp->descr);
	if (x == -1)
		return -1;
	y = PyObject_Hash(wp->self);
	if (y == -1)
		return -1;
	x = x ^ y;
	if (x == -1)
		x = -2;
	return x;
}

913 914 915
static PyObject *
wrapper_repr(wrapperobject *wp)
{
916
	return PyUnicode_FromFormat("<method-wrapper '%s' of %s object at %p>",
917 918 919 920 921 922 923
				   wp->descr->d_base->name,
				   wp->self->ob_type->tp_name,
				   wp->self);
}

static PyMemberDef wrapper_members[] = {
	{"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY},
924 925 926
	{0}
};

927 928 929 930 931 932 933 934 935
static PyObject *
wrapper_objclass(wrapperobject *wp)
{
	PyObject *c = (PyObject *)wp->descr->d_type;

	Py_INCREF(c);
	return c;
}

936 937 938
static PyObject *
wrapper_name(wrapperobject *wp)
{
Neal Norwitz's avatar
Neal Norwitz committed
939
	const char *s = wp->descr->d_base->name;
940

Neal Norwitz's avatar
Neal Norwitz committed
941
	return PyUnicode_FromString(s);
942 943 944 945 946
}

static PyObject *
wrapper_doc(wrapperobject *wp)
{
Neal Norwitz's avatar
Neal Norwitz committed
947
	const char *s = wp->descr->d_base->doc;
948 949 950 951 952 953

	if (s == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
	else {
Neal Norwitz's avatar
Neal Norwitz committed
954
		return PyUnicode_FromString(s);
955 956 957
	}
}

958
static PyGetSetDef wrapper_getsets[] = {
959
	{"__objclass__", (getter)wrapper_objclass},
960 961 962 963 964 965 966 967 968 969 970
	{"__name__", (getter)wrapper_name},
	{"__doc__", (getter)wrapper_doc},
	{0}
};

static PyObject *
wrapper_call(wrapperobject *wp, PyObject *args, PyObject *kwds)
{
	wrapperfunc wrapper = wp->descr->d_base->wrapper;
	PyObject *self = wp->self;

971 972 973 974 975 976 977 978 979 980 981
	if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) {
		wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper;
		return (*wk)(self, args, wp->descr->d_wrapped, kwds);
	}

	if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) {
		PyErr_Format(PyExc_TypeError,
			     "wrapper %s doesn't take keyword arguments",
			     wp->descr->d_base->name);
		return NULL;
	}
982 983 984
	return (*wrapper)(self, args, wp->descr->d_wrapped);
}

985 986 987 988
static int
wrapper_traverse(PyObject *self, visitproc visit, void *arg)
{
	wrapperobject *wp = (wrapperobject *)self;
989 990
	Py_VISIT(wp->descr);
	Py_VISIT(wp->self);
991 992 993
	return 0;
}

994
static PyTypeObject wrappertype = {
995
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
996 997 998 999 1000 1001 1002 1003
	"method-wrapper",			/* tp_name */
	sizeof(wrapperobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	(destructor)wrapper_dealloc, 		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
1004 1005
	(cmpfunc)wrapper_compare,		/* tp_compare */
	(reprfunc)wrapper_repr,			/* tp_repr */
1006 1007 1008
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,		       			/* tp_as_mapping */
1009
	(hashfunc)wrapper_hash,			/* tp_hash */
1010 1011 1012 1013 1014
	(ternaryfunc)wrapper_call,		/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
1015
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1016
 	0,					/* tp_doc */
1017
	wrapper_traverse,			/* tp_traverse */
1018 1019 1020 1021 1022
 	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
1023 1024
	0,					/* tp_methods */
	wrapper_members,			/* tp_members */
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	wrapper_getsets,			/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
};

PyObject *
PyWrapper_New(PyObject *d, PyObject *self)
{
	wrapperobject *wp;
	PyWrapperDescrObject *descr;

	assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type));
	descr = (PyWrapperDescrObject *)d;
	assert(PyObject_IsInstance(self, (PyObject *)(descr->d_type)));

1042
	wp = PyObject_GC_New(wrapperobject, &wrappertype);
1043 1044 1045 1046 1047
	if (wp != NULL) {
		Py_INCREF(descr);
		wp->descr = descr;
		Py_INCREF(self);
		wp->self = self;
1048
		_PyObject_GC_TRACK(wp);
1049 1050 1051
	}
	return (PyObject *)wp;
}
1052 1053


1054
/* A built-in 'property' type */
1055 1056

/*
1057
    class property(object):
1058

1059
        def __init__(self, fget=None, fset=None, fdel=None, doc=None):
1060 1061
            if doc is None and fget is not None and hasattr(fget, "__doc__"):
                doc = fget.__doc__
1062 1063 1064 1065 1066 1067 1068 1069
            self.__get = fget
            self.__set = fset
            self.__del = fdel
            self.__doc__ = doc

        def __get__(self, inst, type=None):
            if inst is None:
                return self
1070 1071
            if self.__get is None:
                raise AttributeError, "unreadable attribute"
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
            return self.__get(inst)

        def __set__(self, inst, value):
            if self.__set is None:
                raise AttributeError, "can't set attribute"
            return self.__set(inst, value)

        def __delete__(self, inst):
            if self.__del is None:
                raise AttributeError, "can't delete attribute"
            return self.__del(inst)

1084 1085 1086 1087
*/

typedef struct {
	PyObject_HEAD
1088 1089 1090 1091
	PyObject *prop_get;
	PyObject *prop_set;
	PyObject *prop_del;
	PyObject *prop_doc;
1092
} propertyobject;
1093

1094 1095 1096 1097 1098 1099 1100 1101 1102
static PyMemberDef property_members[] = {
	{"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY},
	{"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY},
	{"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY},
	{"__doc__",  T_OBJECT, offsetof(propertyobject, prop_doc), READONLY},
	{0}
};


1103
static void
1104
property_dealloc(PyObject *self)
1105
{
1106
	propertyobject *gs = (propertyobject *)self;
1107

1108
	_PyObject_GC_UNTRACK(self);
1109 1110 1111 1112
	Py_XDECREF(gs->prop_get);
	Py_XDECREF(gs->prop_set);
	Py_XDECREF(gs->prop_del);
	Py_XDECREF(gs->prop_doc);
1113 1114 1115 1116
	self->ob_type->tp_free(self);
}

static PyObject *
1117
property_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1118
{
1119
	propertyobject *gs = (propertyobject *)self;
1120 1121 1122 1123 1124

	if (obj == NULL || obj == Py_None) {
		Py_INCREF(self);
		return self;
	}
1125 1126 1127 1128
	if (gs->prop_get == NULL) {
		PyErr_SetString(PyExc_AttributeError, "unreadable attribute");
		return NULL;
	}
1129
	return PyObject_CallFunction(gs->prop_get, "(O)", obj);
1130 1131 1132
}

static int
1133
property_descr_set(PyObject *self, PyObject *obj, PyObject *value)
1134
{
1135
	propertyobject *gs = (propertyobject *)self;
1136
	PyObject *func, *res;
1137

1138
	if (value == NULL)
1139
		func = gs->prop_del;
1140
	else
1141
		func = gs->prop_set;
1142 1143 1144 1145 1146
	if (func == NULL) {
		PyErr_SetString(PyExc_AttributeError,
				value == NULL ?
				"can't delete attribute" :
				"can't set attribute");
1147 1148
		return -1;
	}
1149
	if (value == NULL)
1150
		res = PyObject_CallFunction(func, "(O)", obj);
1151
	else
1152
		res = PyObject_CallFunction(func, "(OO)", obj, value);
1153 1154 1155 1156 1157 1158 1159
	if (res == NULL)
		return -1;
	Py_DECREF(res);
	return 0;
}

static int
1160
property_init(PyObject *self, PyObject *args, PyObject *kwds)
1161
{
1162
	PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL;
1163
	static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0};
1164
	propertyobject *gs = (propertyobject *)self;
1165

1166 1167
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property",
	     				 kwlist, &get, &set, &del, &doc))
1168
		return -1;
1169

1170 1171 1172 1173
	if (get == Py_None)
		get = NULL;
	if (set == Py_None)
		set = NULL;
1174 1175 1176
	if (del == Py_None)
		del = NULL;

1177 1178
	Py_XINCREF(get);
	Py_XINCREF(set);
1179
	Py_XINCREF(del);
1180 1181
	Py_XINCREF(doc);

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
	/* if no docstring given and the getter has one, use that one */
	if ((doc == NULL || doc == Py_None) && get != NULL) {
		PyObject *get_doc = PyObject_GetAttrString(get, "__doc__");
		if (get_doc != NULL) {
			Py_XDECREF(doc);
			doc = get_doc;  /* get_doc already INCREF'd by GetAttr */
		} else {
			PyErr_Clear();
		}
	}

1193 1194 1195 1196 1197
	gs->prop_get = get;
	gs->prop_set = set;
	gs->prop_del = del;
	gs->prop_doc = doc;

1198 1199 1200
	return 0;
}

1201
PyDoc_STRVAR(property_doc,
1202 1203 1204 1205 1206
"property(fget=None, fset=None, fdel=None, doc=None) -> property attribute\n"
"\n"
"fget is a function to be used for getting an attribute value, and likewise\n"
"fset is a function for setting, and fdel a function for del'ing, an\n"
"attribute.  Typical use is to define a managed attribute x:\n"
1207 1208 1209
"class C(object):\n"
"    def getx(self): return self.__x\n"
"    def setx(self, value): self.__x = value\n"
1210
"    def delx(self): del self.__x\n"
1211
"    x = property(getx, setx, delx, \"I'm the 'x' property.\")");
1212

1213 1214 1215 1216
static int
property_traverse(PyObject *self, visitproc visit, void *arg)
{
	propertyobject *pp = (propertyobject *)self;
1217 1218 1219 1220
	Py_VISIT(pp->prop_get);
	Py_VISIT(pp->prop_set);
	Py_VISIT(pp->prop_del);
	Py_VISIT(pp->prop_doc);
1221 1222 1223
	return 0;
}

1224
PyTypeObject PyProperty_Type = {
1225
	PyVarObject_HEAD_INIT(&PyType_Type, 0)
1226 1227
	"property",				/* tp_name */
	sizeof(propertyobject),			/* tp_basicsize */
1228 1229
	0,					/* tp_itemsize */
	/* methods */
1230
	property_dealloc,	 		/* tp_dealloc */
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,		       			/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
1245 1246
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
		Py_TPFLAGS_BASETYPE,		/* tp_flags */
1247
 	property_doc,				/* tp_doc */
1248
	property_traverse,			/* tp_traverse */
1249 1250 1251 1252 1253 1254
 	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	0,					/* tp_methods */
1255
	property_members,			/* tp_members */
1256 1257 1258
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
1259 1260
	property_descr_get,			/* tp_descr_get */
	property_descr_set,			/* tp_descr_set */
1261
	0,					/* tp_dictoffset */
1262
	property_init,				/* tp_init */
1263 1264
	PyType_GenericAlloc,			/* tp_alloc */
	PyType_GenericNew,			/* tp_new */
1265
	PyObject_GC_Del,               		/* tp_free */
1266
};