object.c revision d266eb460e20ded087d01a29da0a230e235afc40
1/***********************************************************
2Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3The Netherlands.
4
5                        All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Stichting Mathematisch
12Centrum or CWI or Corporation for National Research Initiatives or
13CNRI not be used in advertising or publicity pertaining to
14distribution of the software without specific, written prior
15permission.
16
17While CWI is the initial source for this software, a modified version
18is made available by the Corporation for National Research Initiatives
19(CNRI) at the Internet address ftp://ftp.python.org.
20
21STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28PERFORMANCE OF THIS SOFTWARE.
29
30******************************************************************/
31
32/* Generic object operations; and implementation of None (NoObject) */
33
34#include "allobjects.h"
35
36#if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG )
37long ref_total;
38#endif
39
40/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
41   These are used by the individual routines for object creation.
42   Do not call them otherwise, they do not initialize the object! */
43
44#ifdef COUNT_ALLOCS
45static typeobject *type_list;
46extern int tuple_zero_allocs, fast_tuple_allocs;
47extern int quick_int_allocs, quick_neg_int_allocs;
48extern int null_strings, one_strings;
49void
50dump_counts()
51{
52	typeobject *tp;
53
54	for (tp = type_list; tp; tp = tp->tp_next)
55		fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
56			tp->tp_name, tp->tp_alloc, tp->tp_free,
57			tp->tp_maxalloc);
58	fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
59		fast_tuple_allocs, tuple_zero_allocs);
60	fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
61		quick_int_allocs, quick_neg_int_allocs);
62	fprintf(stderr, "null strings: %d, 1-strings: %d\n",
63		null_strings, one_strings);
64}
65
66PyObject *
67get_counts()
68{
69	PyTypeObject *tp;
70	PyObject *result;
71	PyObject *v;
72
73	result = PyList_New(0);
74	if (result == NULL)
75		return NULL;
76	for (tp = type_list; tp; tp = tp->tp_next) {
77		v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_alloc,
78				  tp->tp_free, tp->tp_maxalloc);
79		if (v == NULL) {
80			Py_DECREF(result);
81			return NULL;
82		}
83		if (PyList_Append(result, v) < 0) {
84			Py_DECREF(v);
85			Py_DECREF(result);
86			return NULL;
87		}
88		Py_DECREF(v);
89	}
90	return result;
91}
92
93void
94inc_count(tp)
95	typeobject *tp;
96{
97	if (tp->tp_alloc == 0) {
98		/* first time; insert in linked list */
99		if (tp->tp_next != NULL) /* sanity check */
100			fatal("XXX inc_count sanity check");
101		tp->tp_next = type_list;
102		type_list = tp;
103	}
104	tp->tp_alloc++;
105	if (tp->tp_alloc - tp->tp_free > tp->tp_maxalloc)
106		tp->tp_maxalloc = tp->tp_alloc - tp->tp_free;
107}
108#endif
109
110#ifndef MS_COREDLL
111object *
112newobject(tp)
113	typeobject *tp;
114#else
115object *
116newobject(tp,op)
117	typeobject *tp;
118	PyObject *op;
119#endif
120{
121#ifndef MS_COREDLL
122	object *op = (object *) malloc(tp->tp_basicsize);
123#endif
124	if (op == NULL)
125		return err_nomem();
126	op->ob_type = tp;
127	NEWREF(op);
128	return op;
129}
130
131#ifndef MS_COREDLL
132varobject *
133newvarobject(tp, size)
134	typeobject *tp;
135	int size;
136#else
137varobject *
138newvarobject(tp, size, op)
139	typeobject *tp;
140	int size;
141	varobject *op;
142#endif
143{
144#ifndef MS_COREDLL
145	varobject *op = (varobject *)
146		malloc(tp->tp_basicsize + size * tp->tp_itemsize);
147#endif
148	if (op == NULL)
149		return (varobject *)err_nomem();
150	op->ob_type = tp;
151	op->ob_size = size;
152	NEWREF(op);
153	return op;
154}
155
156int
157printobject(op, fp, flags)
158	object *op;
159	FILE *fp;
160	int flags;
161{
162	int ret = 0;
163	if (sigcheck())
164		return -1;
165	if (op == NULL) {
166		fprintf(fp, "<nil>");
167	}
168	else {
169		if (op->ob_refcnt <= 0)
170			fprintf(fp, "<refcnt %u at %lx>",
171				op->ob_refcnt, (long)op);
172		else if (op->ob_type->tp_print == NULL) {
173			if (op->ob_type->tp_repr == NULL) {
174				fprintf(fp, "<%s object at %lx>",
175					op->ob_type->tp_name, (long)op);
176			}
177			else {
178				object *s;
179				if (flags & PRINT_RAW)
180					s = strobject(op);
181				else
182					s = reprobject(op);
183				if (s == NULL)
184					ret = -1;
185				else if (!is_stringobject(s)) {
186					err_setstr(TypeError,
187						   "repr not string");
188					ret = -1;
189				}
190				else {
191					fprintf(fp, "%s", getstringvalue(s));
192				}
193				XDECREF(s);
194			}
195		}
196		else
197			ret = (*op->ob_type->tp_print)(op, fp, flags);
198	}
199	if (ret == 0) {
200		if (ferror(fp)) {
201			err_errno(IOError);
202			clearerr(fp);
203			ret = -1;
204		}
205	}
206	return ret;
207}
208
209object *
210reprobject(v)
211	object *v;
212{
213	if (sigcheck())
214		return NULL;
215	if (v == NULL)
216		return newstringobject("<NULL>");
217	else if (v->ob_type->tp_repr == NULL) {
218		char buf[120];
219		sprintf(buf, "<%.80s object at %lx>",
220			v->ob_type->tp_name, (long)v);
221		return newstringobject(buf);
222	}
223	else
224		return (*v->ob_type->tp_repr)(v);
225}
226
227object *
228strobject(v)
229	object *v;
230{
231	if (v == NULL)
232		return newstringobject("<NULL>");
233	else if (is_stringobject(v)) {
234		INCREF(v);
235		return v;
236	}
237	else if (v->ob_type->tp_str != NULL)
238		return (*v->ob_type->tp_str)(v);
239	else {
240		object *func;
241		object *res;
242		if (!is_instanceobject(v) ||
243		    (func = getattr(v, "__str__")) == NULL) {
244			err_clear();
245			return reprobject(v);
246		}
247		res = call_object(func, (object *)NULL);
248		DECREF(func);
249		return res;
250	}
251}
252
253static object *
254do_cmp(v, w)
255	object *v, *w;
256{
257	/* __rcmp__ actually won't be called unless __cmp__ isn't defined,
258	   because the check in cmpobject() reverses the objects first.
259	   This is intentional -- it makes no sense to define cmp(x,y) different
260	   than -cmp(y,x). */
261	if (is_instanceobject(v) || is_instanceobject(w))
262		return instancebinop(v, w, "__cmp__", "__rcmp__", do_cmp);
263	return newintobject((long)cmpobject(v, w));
264}
265
266int
267cmpobject(v, w)
268	object *v, *w;
269{
270	typeobject *tp;
271	if (v == w)
272		return 0;
273	if (v == NULL)
274		return -1;
275	if (w == NULL)
276		return 1;
277	if (is_instanceobject(v) || is_instanceobject(w)) {
278		object *res;
279		int c;
280		if (!is_instanceobject(v))
281			return -cmpobject(w, v);
282		res = do_cmp(v, w);
283		if (res == NULL) {
284			err_clear();
285			return (v < w) ? -1 : 1;
286		}
287		if (!is_intobject(res)) {
288			DECREF(res);
289			return (v < w) ? -1 : 1;
290		}
291		c = getintvalue(res);
292		DECREF(res);
293		return (c < 0) ? -1 : (c > 0) ? 1 : 0;
294	}
295	if ((tp = v->ob_type) != w->ob_type) {
296		if (tp->tp_as_number != NULL &&
297				w->ob_type->tp_as_number != NULL) {
298			if (coerce(&v, &w) != 0) {
299				err_clear();
300				/* XXX Should report the error,
301				   XXX but the interface isn't there... */
302			}
303			else {
304				int cmp = (*v->ob_type->tp_compare)(v, w);
305				DECREF(v);
306				DECREF(w);
307				return cmp;
308			}
309		}
310		return strcmp(tp->tp_name, w->ob_type->tp_name);
311	}
312	if (tp->tp_compare == NULL)
313		return (v < w) ? -1 : 1;
314	return (*tp->tp_compare)(v, w);
315}
316
317long
318hashobject(v)
319	object *v;
320{
321	typeobject *tp = v->ob_type;
322	if (tp->tp_hash != NULL)
323		return (*tp->tp_hash)(v);
324	if (tp->tp_compare == NULL)
325		return (long) v; /* Use address as hash value */
326	/* If there's a cmp but no hash defined, the object can't be hashed */
327	err_setstr(TypeError, "unhashable type");
328	return -1;
329}
330
331object *
332getattr(v, name)
333	object *v;
334	char *name;
335{
336	if (v->ob_type->tp_getattro != NULL) {
337		object *w, *res;
338		w = newstringobject(name);
339		if (w == NULL)
340			return NULL;
341		res = (*v->ob_type->tp_getattro)(v, w);
342		XDECREF(w);
343		return res;
344	}
345
346	if (v->ob_type->tp_getattr == NULL) {
347		err_setstr(AttributeError, "attribute-less object");
348		return NULL;
349	}
350	else {
351		return (*v->ob_type->tp_getattr)(v, name);
352	}
353}
354
355int
356hasattr(v, name)
357	object *v;
358	char *name;
359{
360	object *res = getattr(v, name);
361	if (res != NULL) {
362		DECREF(res);
363		return 1;
364	}
365	err_clear();
366	return 0;
367}
368
369int
370setattr(v, name, w)
371	object *v;
372	char *name;
373	object *w;
374{
375	if (v->ob_type->tp_setattro != NULL) {
376		object *s;
377		int res;
378		s = newstringobject(name);
379		if (s == NULL)
380			return -1;
381		res = (*v->ob_type->tp_setattro)(v, s, w);
382		XDECREF(s);
383		return res;
384	}
385
386	if (v->ob_type->tp_setattr == NULL) {
387		if (v->ob_type->tp_getattr == NULL)
388			err_setstr(TypeError,
389				   "attribute-less object (assign or del)");
390		else
391			err_setstr(TypeError,
392				   "object has read-only attributes");
393		return -1;
394	}
395	else {
396		return (*v->ob_type->tp_setattr)(v, name, w);
397	}
398}
399
400/* Test a value used as condition, e.g., in a for or if statement.
401   Return -1 if an error occurred */
402
403int
404testbool(v)
405	object *v;
406{
407	int res;
408	if (v == None)
409		res = 0;
410	else if (v->ob_type->tp_as_number != NULL)
411		res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
412	else if (v->ob_type->tp_as_mapping != NULL)
413		res = (*v->ob_type->tp_as_mapping->mp_length)(v);
414	else if (v->ob_type->tp_as_sequence != NULL)
415		res = (*v->ob_type->tp_as_sequence->sq_length)(v);
416	else
417		res = 1;
418	if (res > 0)
419		res = 1;
420	return res;
421}
422
423/* Coerce two numeric types to the "larger" one.
424   Increment the reference count on each argument.
425   Return -1 and raise an exception if no coercion is possible
426   (and then no reference count is incremented).
427*/
428
429int
430coerce(pv, pw)
431	object **pv, **pw;
432{
433	register object *v = *pv;
434	register object *w = *pw;
435	int res;
436
437	if (v->ob_type == w->ob_type && !is_instanceobject(v)) {
438		INCREF(v);
439		INCREF(w);
440		return 0;
441	}
442	if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
443		res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
444		if (res <= 0)
445			return res;
446	}
447	if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
448		res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
449		if (res <= 0)
450			return res;
451	}
452	err_setstr(TypeError, "number coercion failed");
453	return -1;
454}
455
456
457/* Test whether an object can be called */
458
459int
460callable(x)
461	object *x;
462{
463	if (x == NULL)
464		return 0;
465	if (x->ob_type->tp_call != NULL ||
466	    is_funcobject(x) ||
467	    is_instancemethodobject(x) ||
468	    is_methodobject(x) ||
469	    is_classobject(x))
470		return 1;
471	if (is_instanceobject(x)) {
472		object *call = getattr(x, "__call__");
473		if (call == NULL) {
474			err_clear();
475			return 0;
476		}
477		/* Could test recursively but don't, for fear of endless
478		   recursion if some joker sets self.__call__ = self */
479		DECREF(call);
480		return 1;
481	}
482	return 0;
483}
484
485
486/*
487NoObject is usable as a non-NULL undefined value, used by the macro None.
488There is (and should be!) no way to create other objects of this type,
489so there is exactly one (which is indestructible, by the way).
490*/
491
492/* ARGSUSED */
493static object *
494none_repr(op)
495	object *op;
496{
497	return newstringobject("None");
498}
499
500static typeobject Notype = {
501	OB_HEAD_INIT(&Typetype)
502	0,
503	"None",
504	0,
505	0,
506	0,		/*tp_dealloc*/ /*never called*/
507	0,		/*tp_print*/
508	0,		/*tp_getattr*/
509	0,		/*tp_setattr*/
510	0,		/*tp_compare*/
511	(reprfunc)none_repr, /*tp_repr*/
512	0,		/*tp_as_number*/
513	0,		/*tp_as_sequence*/
514	0,		/*tp_as_mapping*/
515	0,		/*tp_hash */
516};
517
518object NoObject = {
519	OB_HEAD_INIT(&Notype)
520};
521
522
523#ifdef Py_TRACE_REFS
524
525static object refchain = {&refchain, &refchain};
526
527void
528NEWREF(op)
529	object *op;
530{
531	ref_total++;
532	op->ob_refcnt = 1;
533	op->_ob_next = refchain._ob_next;
534	op->_ob_prev = &refchain;
535	refchain._ob_next->_ob_prev = op;
536	refchain._ob_next = op;
537#ifdef COUNT_ALLOCS
538	inc_count(op->ob_type);
539#endif
540}
541
542void
543UNREF(op)
544	register object *op;
545{
546	register object *p;
547	if (op->ob_refcnt < 0)
548		fatal("UNREF negative refcnt");
549	if (op == &refchain ||
550	    op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
551		fatal("UNREF invalid object");
552#ifdef SLOW_UNREF_CHECK
553	for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
554		if (p == op)
555			break;
556	}
557	if (p == &refchain) /* Not found */
558		fatal("UNREF unknown object");
559#endif
560	op->_ob_next->_ob_prev = op->_ob_prev;
561	op->_ob_prev->_ob_next = op->_ob_next;
562	op->_ob_next = op->_ob_prev = NULL;
563#ifdef COUNT_ALLOCS
564	op->ob_type->tp_free++;
565#endif
566}
567
568void
569DELREF(op)
570	object *op;
571{
572	destructor dealloc = op->ob_type->tp_dealloc;
573	UNREF(op);
574	op->ob_type = NULL;
575	(*dealloc)(op);
576}
577
578void
579_Py_PrintReferences(fp)
580	FILE *fp;
581{
582	object *op;
583	fprintf(fp, "Remaining objects (except strings referenced once):\n");
584	for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
585		if (op->ob_refcnt == 1 && is_stringobject(op))
586			continue; /* Will be printed elsewhere */
587		fprintf(fp, "[%d] ", op->ob_refcnt);
588		if (printobject(op, fp, 0) != 0)
589			err_clear();
590		putc('\n', fp);
591	}
592}
593
594PyObject *
595_Py_GetObjects(self, args)
596	PyObject *self;
597	PyObject *args;
598{
599	int i, n;
600	PyObject *t = NULL;
601	PyObject *res, *op;
602
603	if (!PyArg_ParseTuple(args, "i|O", &n, &t))
604		return NULL;
605	op = refchain._ob_next;
606	res = PyList_New(0);
607	if (res == NULL)
608		return NULL;
609	for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
610		while (op == self || op == args || op == res || op == t ||
611		       t != NULL && op->ob_type != (PyTypeObject *) t) {
612			op = op->_ob_next;
613			if (op == &refchain)
614				return res;
615		}
616		if (PyList_Append(res, op) < 0) {
617			Py_DECREF(res);
618			return NULL;
619		}
620		op = op->_ob_next;
621	}
622	return res;
623}
624
625#endif
626
627
628/* Hack to force loading of cobject.o */
629static PyTypeObject *cobject_hack = &PyCObject_Type;
630
631
632/* Hack to force loading of abstract.o */
633static int (*abstract_hack) FPROTO((PyObject *)) = &PyObject_Length;
634