blob: be8eb07d46194f4734450f837c3f222a39fa863b [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jack Jansen28fc8802000-07-11 21:47:20 +00006#ifdef macintosh
7#include "macglue.h"
8#endif
9
Guido van Rossume92e6102000-04-24 15:40:53 +000010/* just for trashcan: */
11#include "compile.h"
12#include "frameobject.h"
13#include "traceback.h"
14
Guido van Rossum6f9e4331995-03-29 16:57:48 +000015#if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG )
Guido van Rossumbffd6832000-01-20 22:32:56 +000016DL_IMPORT(long) _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +000017#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000018
Guido van Rossum393661d2001-08-31 17:40:15 +000019DL_IMPORT(int) Py_DivisionWarningFlag;
20
Guido van Rossum3f5da241990-12-20 15:06:42 +000021/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
22 These are used by the individual routines for object creation.
23 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000024
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000025#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000026static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000027extern int tuple_zero_allocs, fast_tuple_allocs;
28extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000029extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000030void
Fred Drake100814d2000-07-09 15:48:49 +000031dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000032{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000033 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000034
35 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000036 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000037 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000038 tp->tp_maxalloc);
39 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
40 fast_tuple_allocs, tuple_zero_allocs);
41 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
42 quick_int_allocs, quick_neg_int_allocs);
43 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
44 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000045}
46
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000047PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000048get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000049{
50 PyTypeObject *tp;
51 PyObject *result;
52 PyObject *v;
53
54 result = PyList_New(0);
55 if (result == NULL)
56 return NULL;
57 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000058 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
59 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000060 if (v == NULL) {
61 Py_DECREF(result);
62 return NULL;
63 }
64 if (PyList_Append(result, v) < 0) {
65 Py_DECREF(v);
66 Py_DECREF(result);
67 return NULL;
68 }
69 Py_DECREF(v);
70 }
71 return result;
72}
73
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074void
Fred Drake100814d2000-07-09 15:48:49 +000075inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076{
Tim Peters6d6c1a32001-08-02 04:15:00 +000077 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +000078 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000079 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000080 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000081 tp->tp_next = type_list;
82 type_list = tp;
83 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000084 tp->tp_allocs++;
85 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
86 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000087}
88#endif
89
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000091PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092{
Guido van Rossumb18618d2000-05-03 23:44:39 +000093 if (op == NULL) {
94 PyErr_SetString(PyExc_SystemError,
95 "NULL object passed to PyObject_Init");
96 return op;
97 }
98 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101 return op;
102}
103
Guido van Rossumb18618d2000-05-03 23:44:39 +0000104PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000105PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000106{
107 if (op == NULL) {
108 PyErr_SetString(PyExc_SystemError,
109 "NULL object passed to PyObject_InitVar");
110 return op;
111 }
112 /* Any changes should be reflected in PyObject_INIT_VAR */
113 op->ob_size = size;
114 op->ob_type = tp;
115 _Py_NewReference((PyObject *)op);
116 return op;
117}
118
119PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000120_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000121{
122 PyObject *op;
123 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
124 if (op == NULL)
125 return PyErr_NoMemory();
126 return PyObject_INIT(op, tp);
127}
128
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000129PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000130_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000132 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000133 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000134 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000136 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000137 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000138}
139
140void
Fred Drake100814d2000-07-09 15:48:49 +0000141_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000142{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000143 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144}
145
Guido van Rossum90933611991-06-07 16:10:43 +0000146int
Fred Drake100814d2000-07-09 15:48:49 +0000147PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Guido van Rossum278ef591991-07-27 21:40:24 +0000149 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000151 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000152#ifdef USE_STACKCHECK
153 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000154 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000155 return -1;
156 }
157#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000158 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000159 if (op == NULL) {
160 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161 }
Guido van Rossum90933611991-06-07 16:10:43 +0000162 else {
163 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000164 fprintf(fp, "<refcnt %u at %p>",
165 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000166 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000167 PyObject *s;
168 if (flags & Py_PRINT_RAW)
169 s = PyObject_Str(op);
170 else
171 s = PyObject_Repr(op);
172 if (s == NULL)
173 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000174 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000175 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000176 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000177 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000178 }
Guido van Rossum90933611991-06-07 16:10:43 +0000179 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000180 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000181 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000182 if (ret == 0) {
183 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000184 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000185 clearerr(fp);
186 ret = -1;
187 }
188 }
189 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190}
191
Barry Warsaw9bf16442001-01-23 16:24:35 +0000192/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Barry Warsawbbd89b62001-01-24 04:18:13 +0000193void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000194{
Barry Warsaweefb1072001-02-22 22:39:18 +0000195 if (op == NULL)
196 fprintf(stderr, "NULL\n");
197 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000198 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000199 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000200 fprintf(stderr, "\n"
201 "type : %s\n"
202 "refcount: %d\n"
203 "address : %p\n",
204 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
205 op->ob_refcnt,
206 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000207 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000208}
Barry Warsaw903138f2001-01-23 16:33:18 +0000209
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000210PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000211PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000213 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000214 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000215#ifdef USE_STACKCHECK
216 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000217 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000218 return NULL;
219 }
220#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000221 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000222 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000223 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000224 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000225 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000226 else {
227 PyObject *res;
228 res = (*v->ob_type->tp_repr)(v);
229 if (res == NULL)
230 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000231#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000232 if (PyUnicode_Check(res)) {
233 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000234 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000235 Py_DECREF(res);
236 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000237 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000238 else
239 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000240 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000241#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000242 if (!PyString_Check(res)) {
243 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000244 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000245 res->ob_type->tp_name);
246 Py_DECREF(res);
247 return NULL;
248 }
249 return res;
250 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251}
252
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000253PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000254PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000255{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000256 PyObject *res;
257
Guido van Rossumc6004111993-11-05 10:22:19 +0000258 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000259 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000260 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000261 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000262 return v;
263 }
Tim Peters5a49ade2001-09-11 01:41:59 +0000264 if (PyString_Check(v)) {
265 /* For a string subtype that's not a string, return a true
266 string with the same string data. */
267 PyStringObject *s = (PyStringObject *)v;
268 return PyString_FromStringAndSize(s->ob_sval, s->ob_size);
269 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000270 if (v->ob_type->tp_str == NULL)
271 return PyObject_Repr(v);
272
273 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000274 if (res == NULL)
275 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000276#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000277 if (PyUnicode_Check(res)) {
278 PyObject* str;
279 str = PyUnicode_AsEncodedString(res, NULL, NULL);
280 Py_DECREF(res);
281 if (str)
282 res = str;
283 else
284 return NULL;
285 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000286#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000287 if (!PyString_Check(res)) {
288 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000289 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000290 res->ob_type->tp_name);
291 Py_DECREF(res);
292 return NULL;
293 }
294 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000295}
296
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000297#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000298PyObject *
299PyObject_Unicode(PyObject *v)
300{
301 PyObject *res;
302
303 if (v == NULL)
304 res = PyString_FromString("<NULL>");
305 else if (PyUnicode_Check(v)) {
306 Py_INCREF(v);
307 return v;
308 }
Marc-André Lemburgae605342001-03-25 19:16:13 +0000309 else if (PyString_Check(v)) {
310 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000311 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000312 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000313 else if (v->ob_type->tp_str != NULL)
314 res = (*v->ob_type->tp_str)(v);
315 else {
316 PyObject *func;
317 static PyObject *strstr;
318 if (strstr == NULL) {
319 strstr= PyString_InternFromString("__str__");
320 if (strstr == NULL)
321 return NULL;
322 }
323 if (!PyInstance_Check(v) ||
324 (func = PyObject_GetAttr(v, strstr)) == NULL) {
325 PyErr_Clear();
326 res = PyObject_Repr(v);
327 }
328 else {
329 res = PyEval_CallObject(func, (PyObject *)NULL);
330 Py_DECREF(func);
331 }
332 }
333 if (res == NULL)
334 return NULL;
335 if (!PyUnicode_Check(res)) {
336 PyObject* str;
337 str = PyUnicode_FromObject(res);
338 Py_DECREF(res);
339 if (str)
340 res = str;
341 else
342 return NULL;
343 }
344 return res;
345}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000346#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000347
348
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000349/* Macro to get the tp_richcompare field of a type if defined */
350#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
351 ? (t)->tp_richcompare : NULL)
352
Guido van Rossume797ec12001-01-17 15:24:28 +0000353/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
354static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000355
Guido van Rossume797ec12001-01-17 15:24:28 +0000356/* Try a genuine rich comparison, returning an object. Return:
357 NULL for exception;
358 NotImplemented if this particular rich comparison is not implemented or
359 undefined;
360 some object not equal to NotImplemented if it is implemented
361 (this latter object may not be a Boolean).
362*/
363static PyObject *
364try_rich_compare(PyObject *v, PyObject *w, int op)
365{
366 richcmpfunc f;
367 PyObject *res;
368
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000369 if (v->ob_type != w->ob_type &&
370 PyType_IsSubtype(w->ob_type, v->ob_type) &&
371 (f = RICHCOMPARE(w->ob_type)) != NULL) {
372 res = (*f)(w, v, swapped_op[op]);
373 if (res != Py_NotImplemented)
374 return res;
375 Py_DECREF(res);
376 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000377 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000378 res = (*f)(v, w, op);
379 if (res != Py_NotImplemented)
380 return res;
381 Py_DECREF(res);
382 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000383 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000384 return (*f)(w, v, swapped_op[op]);
385 }
386 res = Py_NotImplemented;
387 Py_INCREF(res);
388 return res;
389}
390
391/* Try a genuine rich comparison, returning an int. Return:
392 -1 for exception (including the case where try_rich_compare() returns an
393 object that's not a Boolean);
394 0 if the outcome is false;
395 1 if the outcome is true;
396 2 if this particular rich comparison is not implemented or undefined.
397*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000398static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000399try_rich_compare_bool(PyObject *v, PyObject *w, int op)
400{
401 PyObject *res;
402 int ok;
403
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000404 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000405 return 2; /* Shortcut, avoid INCREF+DECREF */
406 res = try_rich_compare(v, w, op);
407 if (res == NULL)
408 return -1;
409 if (res == Py_NotImplemented) {
410 Py_DECREF(res);
411 return 2;
412 }
413 ok = PyObject_IsTrue(res);
414 Py_DECREF(res);
415 return ok;
416}
417
418/* Try rich comparisons to determine a 3-way comparison. Return:
419 -2 for an exception;
420 -1 if v < w;
421 0 if v == w;
422 1 if v > w;
423 2 if this particular rich comparison is not implemented or undefined.
424*/
425static int
426try_rich_to_3way_compare(PyObject *v, PyObject *w)
427{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000428 static struct { int op; int outcome; } tries[3] = {
429 /* Try this operator, and if it is true, use this outcome: */
430 {Py_EQ, 0},
431 {Py_LT, -1},
432 {Py_GT, 1},
433 };
434 int i;
435
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000436 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000437 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000438
439 for (i = 0; i < 3; i++) {
440 switch (try_rich_compare_bool(v, w, tries[i].op)) {
441 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000442 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000443 case 1:
444 return tries[i].outcome;
445 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000446 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000447
448 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000449}
450
451/* Try a 3-way comparison, returning an int. Return:
452 -2 for an exception;
453 -1 if v < w;
454 0 if v == w;
455 1 if v > w;
456 2 if this particular 3-way comparison is not implemented or undefined.
457*/
458static int
459try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000460{
461 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000462 cmpfunc f;
463
464 /* Comparisons involving instances are given to instance_compare,
465 which has the same return conventions as this function. */
466
Guido van Rossumab3b0342001-09-18 20:38:53 +0000467 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000468 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000469 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000470 if (PyInstance_Check(w))
471 return (*w->ob_type->tp_compare)(v, w);
472
Guido van Rossumab3b0342001-09-18 20:38:53 +0000473 /* If both have the same (non-NULL) tp_compare, use it. */
474 if (f != NULL && f == w->ob_type->tp_compare) {
475 c = (*f)(v, w);
476 if (c < 0 && PyErr_Occurred())
477 return -1;
478 return c < 0 ? -1 : c > 0 ? 1 : 0;
479 }
480
481 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
482 if (f == _PyObject_SlotCompare ||
483 w->ob_type->tp_compare == _PyObject_SlotCompare)
484 return _PyObject_SlotCompare(v, w);
485
Guido van Rossume797ec12001-01-17 15:24:28 +0000486 /* Try coercion; if it fails, give up */
487 c = PyNumber_CoerceEx(&v, &w);
488 if (c < 0)
489 return -2;
490 if (c > 0)
491 return 2;
492
493 /* Try v's comparison, if defined */
494 if ((f = v->ob_type->tp_compare) != NULL) {
495 c = (*f)(v, w);
496 Py_DECREF(v);
497 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000498 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000499 return -2;
500 return c < 0 ? -1 : c > 0 ? 1 : 0;
501 }
502
503 /* Try w's comparison, if defined */
504 if ((f = w->ob_type->tp_compare) != NULL) {
505 c = (*f)(w, v); /* swapped! */
506 Py_DECREF(v);
507 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000508 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000509 return -2;
510 return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
511 }
512
513 /* No comparison defined */
514 Py_DECREF(v);
515 Py_DECREF(w);
516 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000517}
518
Guido van Rossume797ec12001-01-17 15:24:28 +0000519/* Final fallback 3-way comparison, returning an int. Return:
520 -2 if an error occurred;
521 -1 if v < w;
522 0 if v == w;
523 1 if v > w.
524*/
525static int
526default_3way_compare(PyObject *v, PyObject *w)
527{
528 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000529 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000530
531 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000532 /* When comparing these pointers, they must be cast to
533 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
534 * uintptr_t). ANSI specifies that pointer compares other
535 * than == and != to non-related structures are undefined.
536 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000537 Py_uintptr_t vv = (Py_uintptr_t)v;
538 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000539 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
540 }
541
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000542#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000543 /* Special case for Unicode */
544 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
545 c = PyUnicode_Compare(v, w);
546 if (!PyErr_Occurred())
547 return c;
548 /* TypeErrors are ignored: if Unicode coercion fails due
549 to one of the arguments not having the right type, we
550 continue as defined by the coercion protocol (see
551 above). Luckily, decoding errors are reported as
552 ValueErrors and are not masked by this technique. */
553 if (!PyErr_ExceptionMatches(PyExc_TypeError))
554 return -2;
555 PyErr_Clear();
556 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000557#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000558
Guido van Rossum0871e932001-01-22 19:28:09 +0000559 /* None is smaller than anything */
560 if (v == Py_None)
561 return -1;
562 if (w == Py_None)
563 return 1;
564
Guido van Rossume797ec12001-01-17 15:24:28 +0000565 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000566 if (v->ob_type->tp_as_number)
567 vname = "";
568 else
569 vname = v->ob_type->tp_name;
570 if (w->ob_type->tp_as_number)
571 wname = "";
572 else
573 wname = w->ob_type->tp_name;
574 c = strcmp(vname, wname);
575 if (c < 0)
576 return -1;
577 if (c > 0)
578 return 1;
579 /* Same type name, or (more likely) incomparable numeric types */
580 return ((Py_uintptr_t)(v->ob_type) < (
581 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000582}
583
584#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
585
Tim Peters6d60b2e2001-05-07 20:53:51 +0000586/* Do a 3-way comparison, by hook or by crook. Return:
587 -2 for an exception;
588 -1 if v < w;
589 0 if v == w;
590 1 if v > w;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000591 If the object implements a tp_compare function, it returns
592 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000593*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000594static int
Fred Drake100814d2000-07-09 15:48:49 +0000595do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000596{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000597 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000598 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000599
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000600 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000601 && (f = v->ob_type->tp_compare) != NULL) {
602 c = (*f)(v, w);
603 if (c != 2 || !PyInstance_Check(v))
604 return c;
605 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000606 c = try_rich_to_3way_compare(v, w);
607 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000608 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000609 c = try_3way_compare(v, w);
610 if (c < 2)
611 return c;
612 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000613}
614
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000615/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000616 some types) and decremented on exit. If the count exceeds the
617 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000618
619 This is a tunable parameter that should only affect the performance
620 of comparisons, nothing else. Setting it high makes comparing deeply
621 nested non-cyclical data structures faster, but makes comparing cyclical
622 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000623*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000624#define NESTING_LIMIT 20
625
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000626static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000627
628static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000629get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000630{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000631 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000632 PyObject *tstate_dict, *inprogress;
633
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000634 if (key == NULL) {
635 key = PyString_InternFromString("cmp_state");
636 if (key == NULL)
637 return NULL;
638 }
639
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000640 tstate_dict = PyThreadState_GetDict();
641 if (tstate_dict == NULL) {
642 PyErr_BadInternalCall();
643 return NULL;
644 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000645
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000646 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000647 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000648 inprogress = PyDict_New();
649 if (inprogress == NULL)
650 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000651 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000652 Py_DECREF(inprogress);
653 return NULL;
654 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000655 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000656 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000657
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000658 return inprogress;
659}
660
661static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000662check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000663{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000664 PyObject *inprogress;
665 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000666 Py_uintptr_t iv = (Py_uintptr_t)v;
667 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000668 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000669
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000670 inprogress = get_inprogress_dict();
671 if (inprogress == NULL)
672 return NULL;
673
674 token = PyTuple_New(3);
675 if (token == NULL)
676 return NULL;
677
678 if (iv <= iw) {
679 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
680 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
681 if (op >= 0)
682 op = swapped_op[op];
683 } else {
684 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
685 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
686 }
687 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
688 if (x == NULL || y == NULL || z == NULL) {
689 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000690 return NULL;
691 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000692
693 if (PyDict_GetItem(inprogress, token) != NULL) {
694 Py_DECREF(token);
695 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000696 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000697
698 if (PyDict_SetItem(inprogress, token, token) < 0) {
699 Py_DECREF(token);
700 return NULL;
701 }
702
703 return token;
704}
705
706static void
707delete_token(PyObject *token)
708{
709 PyObject *inprogress;
710
711 if (token == NULL || token == Py_None)
712 return;
713 inprogress = get_inprogress_dict();
714 if (inprogress == NULL)
715 PyErr_Clear();
716 else
717 PyDict_DelItem(inprogress, token);
718 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000719}
720
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721int
Fred Drake100814d2000-07-09 15:48:49 +0000722PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000724 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000725 int result;
726
Jack Jansend49cbe12000-08-22 21:52:51 +0000727#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000728 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000729 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
730 return -1;
731 }
732#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000733 if (v == NULL || w == NULL) {
734 PyErr_BadInternalCall();
735 return -1;
736 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737 if (v == w)
738 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000739 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000740 compare_nesting++;
741 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000742 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000743 || (vtp->tp_as_sequence
744 && !PyString_Check(v)
745 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000746 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000747 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000748
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000749 if (token == NULL) {
750 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000751 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000752 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000753 /* already comparing these objects. assume
754 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000755 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000756 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000757 else {
758 result = do_cmp(v, w);
759 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000760 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000761 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000762 else {
763 result = do_cmp(v, w);
764 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000765 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000766 return result < 0 ? -1 : result;
767}
768
769static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000770convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000771{
Guido van Rossume797ec12001-01-17 15:24:28 +0000772 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000773 switch (op) {
774 case Py_LT: c = c < 0; break;
775 case Py_LE: c = c <= 0; break;
776 case Py_EQ: c = c == 0; break;
777 case Py_NE: c = c != 0; break;
778 case Py_GT: c = c > 0; break;
779 case Py_GE: c = c >= 0; break;
780 }
781 result = c ? Py_True : Py_False;
782 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000783 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000784}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000785
786
787static PyObject *
788try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
789{
790 int c;
791
792 c = try_3way_compare(v, w);
793 if (c >= 2)
794 c = default_3way_compare(v, w);
795 if (c <= -2)
796 return NULL;
797 return convert_3way_to_object(op, c);
798}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000800static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000801do_richcmp(PyObject *v, PyObject *w, int op)
802{
803 PyObject *res;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000804 cmpfunc f;
805
806 /* If the types are equal, don't bother with coercions etc.
807 Instances are special-cased in try_3way_compare, since
808 a result of 2 does *not* mean one value being greater
809 than the other. */
810 if (v->ob_type == w->ob_type
811 && (f = v->ob_type->tp_compare) != NULL
812 && !PyInstance_Check(v)) {
813 int c;
814 richcmpfunc f1;
815 if ((f1 = RICHCOMPARE(v->ob_type)) != NULL) {
816 /* If the type has richcmp, try it first.
817 try_rich_compare would try it two-sided,
818 which is not needed since we've a single
819 type only. */
820 res = (*f1)(v, w, op);
821 if (res != Py_NotImplemented)
822 return res;
823 Py_DECREF(res);
824 }
825 c = (*f)(v, w);
826 if (c < 0 && PyErr_Occurred())
827 return NULL;
828 return convert_3way_to_object(op, c);
829 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000830
831 res = try_rich_compare(v, w, op);
832 if (res != Py_NotImplemented)
833 return res;
834 Py_DECREF(res);
835
836 return try_3way_to_rich_compare(v, w, op);
837}
838
839PyObject *
840PyObject_RichCompare(PyObject *v, PyObject *w, int op)
841{
842 PyObject *res;
843
844 assert(Py_LT <= op && op <= Py_GE);
845
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000846 compare_nesting++;
847 if (compare_nesting > NESTING_LIMIT &&
848 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000849 || (v->ob_type->tp_as_sequence
850 && !PyString_Check(v)
851 && !PyTuple_Check(v)))) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000852 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000853 PyObject *token = check_recursion(v, w, op);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000854
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000855 if (token == NULL) {
856 res = NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000857 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000858 else if (token == Py_None) {
859 /* already comparing these objects with this operator.
860 assume they're equal until shown otherwise */
861 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000862 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000863 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000864 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000865 else {
866 PyErr_SetString(PyExc_ValueError,
867 "can't order recursive values");
868 res = NULL;
869 }
870 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000871 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000872 else {
873 res = do_richcmp(v, w, op);
874 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000875 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000876 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000877 else {
878 res = do_richcmp(v, w, op);
879 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000880 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000881 return res;
882}
883
Tim Petersde9725f2001-05-05 10:06:17 +0000884/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000885int
886PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
887{
888 PyObject *res = PyObject_RichCompare(v, w, op);
889 int ok;
890
891 if (res == NULL)
892 return -1;
893 ok = PyObject_IsTrue(res);
894 Py_DECREF(res);
895 return ok;
896}
Fred Drake13634cf2000-06-29 19:17:04 +0000897
898/* Set of hash utility functions to help maintaining the invariant that
899 iff a==b then hash(a)==hash(b)
900
901 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
902*/
903
904long
Fred Drake100814d2000-07-09 15:48:49 +0000905_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000906{
Tim Peters39dce292000-08-15 03:34:48 +0000907 double intpart, fractpart;
908 int expo;
909 long hipart;
910 long x; /* the final hash value */
911 /* This is designed so that Python numbers of different types
912 * that compare equal hash to the same value; otherwise comparisons
913 * of mapping keys will turn out weird.
914 */
915
916#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
917{
918 extended e;
919 fractpart = modf(v, &e);
920 intpart = e;
921}
922#else
923 fractpart = modf(v, &intpart);
924#endif
925 if (fractpart == 0.0) {
926 /* This must return the same hash as an equal int or long. */
927 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
928 /* Convert to long and use its hash. */
929 PyObject *plong; /* converted to Python long */
930 if (Py_IS_INFINITY(intpart))
931 /* can't convert to long int -- arbitrary */
932 v = v < 0 ? -271828.0 : 314159.0;
933 plong = PyLong_FromDouble(v);
934 if (plong == NULL)
935 return -1;
936 x = PyObject_Hash(plong);
937 Py_DECREF(plong);
938 return x;
939 }
940 /* Fits in a C long == a Python int, so is its own hash. */
941 x = (long)intpart;
942 if (x == -1)
943 x = -2;
944 return x;
945 }
946 /* The fractional part is non-zero, so we don't have to worry about
947 * making this match the hash of some other type.
948 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000949 * Since the VAX D double format has 56 mantissa bits, which is the
950 * most of any double format in use, each of these parts may have as
951 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000952 * So, assuming sizeof(long) >= 4, each part can be broken into two
953 * longs; frexp and multiplication are used to do that.
954 * Also, since the Cray double format has 15 exponent bits, which is
955 * the most of any double format in use, shifting the exponent field
956 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000957 */
Tim Peters39dce292000-08-15 03:34:48 +0000958 v = frexp(v, &expo);
959 v *= 2147483648.0; /* 2**31 */
960 hipart = (long)v; /* take the top 32 bits */
961 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
962 x = hipart + (long)v + (expo << 15);
963 if (x == -1)
964 x = -2;
965 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000966}
967
968long
Fred Drake100814d2000-07-09 15:48:49 +0000969_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000970{
971#if SIZEOF_LONG >= SIZEOF_VOID_P
972 return (long)p;
973#else
974 /* convert to a Python long and hash that */
975 PyObject* longobj;
976 long x;
977
978 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
979 x = -1;
980 goto finally;
981 }
982 x = PyObject_Hash(longobj);
983
984finally:
985 Py_XDECREF(longobj);
986 return x;
987#endif
988}
989
990
Guido van Rossum9bfef441993-03-29 10:43:31 +0000991long
Fred Drake100814d2000-07-09 15:48:49 +0000992PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000993{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000994 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000995 if (tp->tp_hash != NULL)
996 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000997 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000998 return _Py_HashPointer(v); /* Use address as hash value */
999 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001000 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001001 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001002 return -1;
1003}
1004
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001005PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001006PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001007{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001008 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001009
Tim Peters6d6c1a32001-08-02 04:15:00 +00001010 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001011 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012 w = PyString_InternFromString(name);
1013 if (w == NULL)
1014 return NULL;
1015 res = PyObject_GetAttr(v, w);
1016 Py_XDECREF(w);
1017 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001018}
1019
1020int
Fred Drake100814d2000-07-09 15:48:49 +00001021PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001022{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001023 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001024 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001025 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001026 return 1;
1027 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001028 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001029 return 0;
1030}
1031
1032int
Fred Drake100814d2000-07-09 15:48:49 +00001033PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001034{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 PyObject *s;
1036 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001037
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001039 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001040 s = PyString_InternFromString(name);
1041 if (s == NULL)
1042 return -1;
1043 res = PyObject_SetAttr(v, s, w);
1044 Py_XDECREF(s);
1045 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001046}
1047
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001048PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001049PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001050{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051 PyTypeObject *tp = v->ob_type;
1052
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001053#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001054 /* The Unicode to string conversion is done here because the
1055 existing tp_getattro slots expect a string object as name
1056 and we wouldn't want to break those. */
1057 if (PyUnicode_Check(name)) {
1058 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1059 if (name == NULL)
1060 return NULL;
1061 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001062#endif
1063
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001064 if (!PyString_Check(name)) {
1065 PyErr_SetString(PyExc_TypeError,
1066 "attribute name must be string");
1067 return NULL;
1068 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069 if (tp->tp_getattro != NULL)
1070 return (*tp->tp_getattro)(v, name);
1071 if (tp->tp_getattr != NULL)
1072 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1073 PyErr_Format(PyExc_AttributeError,
1074 "'%.50s' object has no attribute '%.400s'",
1075 tp->tp_name, PyString_AS_STRING(name));
1076 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001077}
1078
1079int
Fred Drake100814d2000-07-09 15:48:49 +00001080PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001081{
1082 PyObject *res = PyObject_GetAttr(v, name);
1083 if (res != NULL) {
1084 Py_DECREF(res);
1085 return 1;
1086 }
1087 PyErr_Clear();
1088 return 0;
1089}
1090
1091int
Fred Drake100814d2000-07-09 15:48:49 +00001092PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001093{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001095 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001096
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001097#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001098 /* The Unicode to string conversion is done here because the
1099 existing tp_setattro slots expect a string object as name
1100 and we wouldn't want to break those. */
1101 if (PyUnicode_Check(name)) {
1102 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1103 if (name == NULL)
1104 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001105 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001106 else
1107#endif
1108 if (!PyString_Check(name)){
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001109 PyErr_SetString(PyExc_TypeError,
1110 "attribute name must be string");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 else
1114 Py_INCREF(name);
1115
1116 PyString_InternInPlace(&name);
1117 if (tp->tp_setattro != NULL) {
1118 err = (*tp->tp_setattro)(v, name, value);
1119 Py_DECREF(name);
1120 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001121 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 if (tp->tp_setattr != NULL) {
1123 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1124 Py_DECREF(name);
1125 return err;
1126 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001127 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1129 PyErr_Format(PyExc_TypeError,
1130 "'%.100s' object has no attributes "
1131 "(%s .%.100s)",
1132 tp->tp_name,
1133 value==NULL ? "del" : "assign to",
1134 PyString_AS_STRING(name));
1135 else
1136 PyErr_Format(PyExc_TypeError,
1137 "'%.100s' object has only read-only attributes "
1138 "(%s .%.100s)",
1139 tp->tp_name,
1140 value==NULL ? "del" : "assign to",
1141 PyString_AS_STRING(name));
1142 return -1;
1143}
1144
1145/* Helper to get a pointer to an object's __dict__ slot, if any */
1146
1147PyObject **
1148_PyObject_GetDictPtr(PyObject *obj)
1149{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 long dictoffset;
1151 PyTypeObject *tp = obj->ob_type;
1152
1153 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1154 return NULL;
1155 dictoffset = tp->tp_dictoffset;
1156 if (dictoffset == 0)
1157 return NULL;
1158 if (dictoffset < 0) {
Tim Petersf2a67da2001-10-07 03:54:51 +00001159 const size_t size = _PyObject_VAR_SIZE(tp,
1160 ((PyVarObject *)obj)->ob_size);
Tim Peters6d483d32001-10-06 21:27:34 +00001161 dictoffset += (long)size;
1162 assert(dictoffset > 0);
1163 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 }
1165 return (PyObject **) ((char *)obj + dictoffset);
1166}
1167
1168/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1169
1170PyObject *
1171PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1172{
1173 PyTypeObject *tp = obj->ob_type;
1174 PyObject *descr;
1175 descrgetfunc f;
1176 PyObject **dictptr;
1177
1178 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001179 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 return NULL;
1181 }
1182
1183 descr = _PyType_Lookup(tp, name);
1184 f = NULL;
1185 if (descr != NULL) {
1186 f = descr->ob_type->tp_descr_get;
1187 if (f != NULL && PyDescr_IsData(descr))
1188 return f(descr, obj, (PyObject *)obj->ob_type);
1189 }
1190
1191 dictptr = _PyObject_GetDictPtr(obj);
1192 if (dictptr != NULL) {
1193 PyObject *dict = *dictptr;
1194 if (dict != NULL) {
1195 PyObject *res = PyDict_GetItem(dict, name);
1196 if (res != NULL) {
1197 Py_INCREF(res);
1198 return res;
1199 }
1200 }
1201 }
1202
1203 if (f != NULL)
1204 return f(descr, obj, (PyObject *)obj->ob_type);
1205
1206 if (descr != NULL) {
1207 Py_INCREF(descr);
1208 return descr;
1209 }
1210
1211 PyErr_Format(PyExc_AttributeError,
1212 "'%.50s' object has no attribute '%.400s'",
1213 tp->tp_name, PyString_AS_STRING(name));
1214 return NULL;
1215}
1216
1217int
1218PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1219{
1220 PyTypeObject *tp = obj->ob_type;
1221 PyObject *descr;
1222 descrsetfunc f;
1223 PyObject **dictptr;
1224
1225 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001226 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227 return -1;
1228 }
1229
1230 descr = _PyType_Lookup(tp, name);
1231 f = NULL;
1232 if (descr != NULL) {
1233 f = descr->ob_type->tp_descr_set;
1234 if (f != NULL && PyDescr_IsData(descr))
1235 return f(descr, obj, value);
1236 }
1237
1238 dictptr = _PyObject_GetDictPtr(obj);
1239 if (dictptr != NULL) {
1240 PyObject *dict = *dictptr;
1241 if (dict == NULL && value != NULL) {
1242 dict = PyDict_New();
1243 if (dict == NULL)
1244 return -1;
1245 *dictptr = dict;
1246 }
1247 if (dict != NULL) {
1248 int res;
1249 if (value == NULL)
1250 res = PyDict_DelItem(dict, name);
1251 else
1252 res = PyDict_SetItem(dict, name, value);
1253 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1254 PyErr_SetObject(PyExc_AttributeError, name);
1255 return res;
1256 }
1257 }
1258
1259 if (f != NULL)
1260 return f(descr, obj, value);
1261
1262 if (descr == NULL) {
1263 PyErr_Format(PyExc_AttributeError,
1264 "'%.50s' object has no attribute '%.400s'",
1265 tp->tp_name, PyString_AS_STRING(name));
1266 return -1;
1267 }
1268
1269 PyErr_Format(PyExc_AttributeError,
1270 "'%.50s' object attribute '%.400s' is read-only",
1271 tp->tp_name, PyString_AS_STRING(name));
1272 return -1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001273}
1274
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001275/* Test a value used as condition, e.g., in a for or if statement.
1276 Return -1 if an error occurred */
1277
1278int
Fred Drake100814d2000-07-09 15:48:49 +00001279PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001280{
1281 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001282 if (v == Py_None)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001283 res = 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001284 else if (v->ob_type->tp_as_number != NULL &&
1285 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001286 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001287 else if (v->ob_type->tp_as_mapping != NULL &&
1288 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001289 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001290 else if (v->ob_type->tp_as_sequence != NULL &&
1291 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001292 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1293 else
1294 res = 1;
1295 if (res > 0)
1296 res = 1;
1297 return res;
1298}
1299
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001300/* equivalent of 'not v'
1301 Return -1 if an error occurred */
1302
1303int
Fred Drake100814d2000-07-09 15:48:49 +00001304PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001305{
1306 int res;
1307 res = PyObject_IsTrue(v);
1308 if (res < 0)
1309 return res;
1310 return res == 0;
1311}
1312
Guido van Rossum5524a591995-01-10 15:26:20 +00001313/* Coerce two numeric types to the "larger" one.
1314 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001315 Return value:
1316 -1 if an error occurred;
1317 0 if the coercion succeeded (and then the reference counts are increased);
1318 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001319*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001320int
Fred Drake100814d2000-07-09 15:48:49 +00001321PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001322{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001323 register PyObject *v = *pv;
1324 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001325 int res;
1326
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001327 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1328 Py_INCREF(v);
1329 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001330 return 0;
1331 }
1332 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1333 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1334 if (res <= 0)
1335 return res;
1336 }
1337 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1338 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1339 if (res <= 0)
1340 return res;
1341 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001342 return 1;
1343}
1344
Guido van Rossume797ec12001-01-17 15:24:28 +00001345/* Coerce two numeric types to the "larger" one.
1346 Increment the reference count on each argument.
1347 Return -1 and raise an exception if no coercion is possible
1348 (and then no reference count is incremented).
1349*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001350int
Fred Drake100814d2000-07-09 15:48:49 +00001351PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001352{
1353 int err = PyNumber_CoerceEx(pv, pw);
1354 if (err <= 0)
1355 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001356 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001357 return -1;
1358}
1359
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001360
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001361/* Test whether an object can be called */
1362
1363int
Fred Drake100814d2000-07-09 15:48:49 +00001364PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001365{
1366 if (x == NULL)
1367 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001368 if (PyInstance_Check(x)) {
1369 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001370 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001371 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001372 return 0;
1373 }
1374 /* Could test recursively but don't, for fear of endless
1375 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001377 return 1;
1378 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001379 else {
1380 return x->ob_type->tp_call != NULL;
1381 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001382}
1383
Tim Peters7eea37e2001-09-04 22:08:56 +00001384/* Helper for PyObject_Dir.
1385 Merge the __dict__ of aclass into dict, and recursively also all
1386 the __dict__s of aclass's base classes. The order of merging isn't
1387 defined, as it's expected that only the final set of dict keys is
1388 interesting.
1389 Return 0 on success, -1 on error.
1390*/
1391
1392static int
1393merge_class_dict(PyObject* dict, PyObject* aclass)
1394{
1395 PyObject *classdict;
1396 PyObject *bases;
1397
1398 assert(PyDict_Check(dict));
1399 assert(aclass);
1400
1401 /* Merge in the type's dict (if any). */
1402 classdict = PyObject_GetAttrString(aclass, "__dict__");
1403 if (classdict == NULL)
1404 PyErr_Clear();
1405 else {
1406 int status = PyDict_Update(dict, classdict);
1407 Py_DECREF(classdict);
1408 if (status < 0)
1409 return -1;
1410 }
1411
1412 /* Recursively merge in the base types' (if any) dicts. */
1413 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001414 if (bases == NULL)
1415 PyErr_Clear();
1416 else {
Tim Peters7eea37e2001-09-04 22:08:56 +00001417 int i, n;
1418 assert(PyTuple_Check(bases));
1419 n = PyTuple_GET_SIZE(bases);
1420 for (i = 0; i < n; i++) {
1421 PyObject *base = PyTuple_GET_ITEM(bases, i);
1422 if (merge_class_dict(dict, base) < 0) {
1423 Py_DECREF(bases);
1424 return -1;
1425 }
1426 }
1427 Py_DECREF(bases);
1428 }
1429 return 0;
1430}
1431
Tim Peters305b5852001-09-17 02:38:46 +00001432/* Helper for PyObject_Dir.
1433 If obj has an attr named attrname that's a list, merge its string
1434 elements into keys of dict.
1435 Return 0 on success, -1 on error. Errors due to not finding the attr,
1436 or the attr not being a list, are suppressed.
1437*/
1438
1439static int
1440merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1441{
1442 PyObject *list;
1443 int result = 0;
1444
1445 assert(PyDict_Check(dict));
1446 assert(obj);
1447 assert(attrname);
1448
1449 list = PyObject_GetAttrString(obj, attrname);
1450 if (list == NULL)
1451 PyErr_Clear();
1452
1453 else if (PyList_Check(list)) {
1454 int i;
1455 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1456 PyObject *item = PyList_GET_ITEM(list, i);
1457 if (PyString_Check(item)) {
1458 result = PyDict_SetItem(dict, item, Py_None);
1459 if (result < 0)
1460 break;
1461 }
1462 }
1463 }
1464
1465 Py_XDECREF(list);
1466 return result;
1467}
1468
Tim Peters7eea37e2001-09-04 22:08:56 +00001469/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1470 docstring, which should be kept in synch with this implementation. */
1471
1472PyObject *
1473PyObject_Dir(PyObject *arg)
1474{
1475 /* Set exactly one of these non-NULL before the end. */
1476 PyObject *result = NULL; /* result list */
1477 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1478
1479 /* If NULL arg, return the locals. */
1480 if (arg == NULL) {
1481 PyObject *locals = PyEval_GetLocals();
1482 if (locals == NULL)
1483 goto error;
1484 result = PyDict_Keys(locals);
1485 if (result == NULL)
1486 goto error;
1487 }
1488
1489 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001490 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001491 masterdict = PyObject_GetAttrString(arg, "__dict__");
1492 if (masterdict == NULL)
1493 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001494 if (!PyDict_Check(masterdict)) {
1495 PyErr_SetString(PyExc_TypeError,
1496 "module.__dict__ is not a dictionary");
1497 goto error;
1498 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001499 }
1500
1501 /* Elif some form of type or class, grab its dict and its bases.
1502 We deliberately don't suck up its __class__, as methods belonging
1503 to the metaclass would probably be more confusing than helpful. */
1504 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1505 masterdict = PyDict_New();
1506 if (masterdict == NULL)
1507 goto error;
1508 if (merge_class_dict(masterdict, arg) < 0)
1509 goto error;
1510 }
1511
1512 /* Else look at its dict, and the attrs reachable from its class. */
1513 else {
1514 PyObject *itsclass;
1515 /* Create a dict to start with. CAUTION: Not everything
1516 responding to __dict__ returns a dict! */
1517 masterdict = PyObject_GetAttrString(arg, "__dict__");
1518 if (masterdict == NULL) {
1519 PyErr_Clear();
1520 masterdict = PyDict_New();
1521 }
1522 else if (!PyDict_Check(masterdict)) {
1523 Py_DECREF(masterdict);
1524 masterdict = PyDict_New();
1525 }
1526 else {
1527 /* The object may have returned a reference to its
1528 dict, so copy it to avoid mutating it. */
1529 PyObject *temp = PyDict_Copy(masterdict);
1530 Py_DECREF(masterdict);
1531 masterdict = temp;
1532 }
1533 if (masterdict == NULL)
1534 goto error;
1535
Tim Peters305b5852001-09-17 02:38:46 +00001536 /* Merge in __members__ and __methods__ (if any).
1537 XXX Would like this to go away someday; for now, it's
1538 XXX needed to get at im_self etc of method objects. */
1539 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1540 goto error;
1541 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1542 goto error;
1543
Tim Peters7eea37e2001-09-04 22:08:56 +00001544 /* Merge in attrs reachable from its class.
1545 CAUTION: Not all objects have a __class__ attr. */
1546 itsclass = PyObject_GetAttrString(arg, "__class__");
1547 if (itsclass == NULL)
1548 PyErr_Clear();
1549 else {
1550 int status = merge_class_dict(masterdict, itsclass);
1551 Py_DECREF(itsclass);
1552 if (status < 0)
1553 goto error;
1554 }
1555 }
1556
1557 assert((result == NULL) ^ (masterdict == NULL));
1558 if (masterdict != NULL) {
1559 /* The result comes from its keys. */
1560 assert(result == NULL);
1561 result = PyDict_Keys(masterdict);
1562 if (result == NULL)
1563 goto error;
1564 }
1565
1566 assert(result);
1567 if (PyList_Sort(result) != 0)
1568 goto error;
1569 else
1570 goto normal_return;
1571
1572 error:
1573 Py_XDECREF(result);
1574 result = NULL;
1575 /* fall through */
1576 normal_return:
1577 Py_XDECREF(masterdict);
1578 return result;
1579}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001580
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001581/*
1582NoObject is usable as a non-NULL undefined value, used by the macro None.
1583There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001584so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001585(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001586*/
1587
Guido van Rossum0c182a11992-03-27 17:26:13 +00001588/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001589static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001590none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001591{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001592 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001593}
1594
Barry Warsaw9bf16442001-01-23 16:24:35 +00001595/* ARGUSED */
1596static void
1597none_dealloc(PyObject* ignore)
1598{
1599 /* This should never get called, but we also don't want to SEGV if
1600 * we accidently decref None out of existance.
1601 */
1602 abort();
1603}
1604
1605
Guido van Rossumba21a492001-08-16 08:17:26 +00001606static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001607 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001608 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001609 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001610 0,
1611 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001612 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001613 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001614 0, /*tp_getattr*/
1615 0, /*tp_setattr*/
1616 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001617 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001618 0, /*tp_as_number*/
1619 0, /*tp_as_sequence*/
1620 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001621 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001622};
1623
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001624PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001625 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001626};
1627
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001628/* NotImplemented is an object that can be used to signal that an
1629 operation is not implemented for the given type combination. */
1630
1631static PyObject *
1632NotImplemented_repr(PyObject *op)
1633{
1634 return PyString_FromString("NotImplemented");
1635}
1636
1637static PyTypeObject PyNotImplemented_Type = {
1638 PyObject_HEAD_INIT(&PyType_Type)
1639 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001640 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001641 0,
1642 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001643 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001644 0, /*tp_print*/
1645 0, /*tp_getattr*/
1646 0, /*tp_setattr*/
1647 0, /*tp_compare*/
1648 (reprfunc)NotImplemented_repr, /*tp_repr*/
1649 0, /*tp_as_number*/
1650 0, /*tp_as_sequence*/
1651 0, /*tp_as_mapping*/
1652 0, /*tp_hash */
1653};
1654
1655PyObject _Py_NotImplementedStruct = {
1656 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1657};
1658
Guido van Rossumba21a492001-08-16 08:17:26 +00001659void
1660_Py_ReadyTypes(void)
1661{
1662 if (PyType_Ready(&PyType_Type) < 0)
1663 Py_FatalError("Can't initialize 'type'");
1664
1665 if (PyType_Ready(&PyList_Type) < 0)
1666 Py_FatalError("Can't initialize 'list'");
1667
1668 if (PyType_Ready(&PyNone_Type) < 0)
1669 Py_FatalError("Can't initialize type(None)");
1670
1671 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1672 Py_FatalError("Can't initialize type(NotImplemented)");
1673}
1674
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001675
Guido van Rossum84a90321996-05-22 16:34:47 +00001676#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001677
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001678static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001679
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001680void
Fred Drake100814d2000-07-09 15:48:49 +00001681_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001682{
1683 refchain._ob_prev = refchain._ob_next = &refchain;
1684 _Py_RefTotal = 0;
1685}
1686
1687void
Fred Drake100814d2000-07-09 15:48:49 +00001688_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001689{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001690 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001691 op->ob_refcnt = 1;
1692 op->_ob_next = refchain._ob_next;
1693 op->_ob_prev = &refchain;
1694 refchain._ob_next->_ob_prev = op;
1695 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001696#ifdef COUNT_ALLOCS
1697 inc_count(op->ob_type);
1698#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001699}
1700
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001701void
Fred Drake100814d2000-07-09 15:48:49 +00001702_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001703{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001704#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001705 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001706#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001707 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001708 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001709 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001710 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001711 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001712#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001713 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1714 if (p == op)
1715 break;
1716 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001717 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001718 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001719#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001720 op->_ob_next->_ob_prev = op->_ob_prev;
1721 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001722 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001723#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001724 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001725#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001726}
1727
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001728void
Fred Drake100814d2000-07-09 15:48:49 +00001729_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001730{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001731 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001732 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001733 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001734}
1735
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001736void
Fred Drake100814d2000-07-09 15:48:49 +00001737_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001738{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001739 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001740 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001741 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1742 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001743 if (PyObject_Print(op, fp, 0) != 0)
1744 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001745 putc('\n', fp);
1746 }
1747}
1748
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001749PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001750_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001751{
1752 int i, n;
1753 PyObject *t = NULL;
1754 PyObject *res, *op;
1755
1756 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1757 return NULL;
1758 op = refchain._ob_next;
1759 res = PyList_New(0);
1760 if (res == NULL)
1761 return NULL;
1762 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1763 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001764 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001765 op = op->_ob_next;
1766 if (op == &refchain)
1767 return res;
1768 }
1769 if (PyList_Append(res, op) < 0) {
1770 Py_DECREF(res);
1771 return NULL;
1772 }
1773 op = op->_ob_next;
1774 }
1775 return res;
1776}
1777
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001778#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001779
1780
1781/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001782PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001783
1784
1785/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001786int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001787
1788
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001789/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001790
Thomas Wouters334fb892000-07-25 12:56:38 +00001791void *
Fred Drake100814d2000-07-09 15:48:49 +00001792PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001793{
1794#if _PyMem_EXTRA > 0
1795 if (nbytes == 0)
1796 nbytes = _PyMem_EXTRA;
1797#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001798 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001799}
1800
Thomas Wouters334fb892000-07-25 12:56:38 +00001801void *
1802PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001803{
1804#if _PyMem_EXTRA > 0
1805 if (nbytes == 0)
1806 nbytes = _PyMem_EXTRA;
1807#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001808 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001809}
1810
1811void
Thomas Wouters334fb892000-07-25 12:56:38 +00001812PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001813{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001814 PyMem_FREE(p);
1815}
1816
1817
1818/* Python's object malloc wrappers (see objimpl.h) */
1819
Thomas Wouters334fb892000-07-25 12:56:38 +00001820void *
Fred Drake100814d2000-07-09 15:48:49 +00001821PyObject_Malloc(size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001822{
1823 return PyObject_MALLOC(nbytes);
1824}
1825
Thomas Wouters334fb892000-07-25 12:56:38 +00001826void *
1827PyObject_Realloc(void *p, size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001828{
1829 return PyObject_REALLOC(p, nbytes);
1830}
1831
1832void
Thomas Wouters334fb892000-07-25 12:56:38 +00001833PyObject_Free(void *p)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001834{
1835 PyObject_FREE(p);
Guido van Rossume09fb551997-08-05 02:04:34 +00001836}
Guido van Rossum86610361998-04-10 22:32:46 +00001837
1838
1839/* These methods are used to control infinite recursion in repr, str, print,
1840 etc. Container objects that may recursively contain themselves,
1841 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1842 Py_ReprLeave() to avoid infinite recursion.
1843
1844 Py_ReprEnter() returns 0 the first time it is called for a particular
1845 object and 1 every time thereafter. It returns -1 if an exception
1846 occurred. Py_ReprLeave() has no return value.
1847
1848 See dictobject.c and listobject.c for examples of use.
1849*/
1850
1851#define KEY "Py_Repr"
1852
1853int
Fred Drake100814d2000-07-09 15:48:49 +00001854Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001855{
1856 PyObject *dict;
1857 PyObject *list;
1858 int i;
1859
1860 dict = PyThreadState_GetDict();
1861 if (dict == NULL)
1862 return -1;
1863 list = PyDict_GetItemString(dict, KEY);
1864 if (list == NULL) {
1865 list = PyList_New(0);
1866 if (list == NULL)
1867 return -1;
1868 if (PyDict_SetItemString(dict, KEY, list) < 0)
1869 return -1;
1870 Py_DECREF(list);
1871 }
1872 i = PyList_GET_SIZE(list);
1873 while (--i >= 0) {
1874 if (PyList_GET_ITEM(list, i) == obj)
1875 return 1;
1876 }
1877 PyList_Append(list, obj);
1878 return 0;
1879}
1880
1881void
Fred Drake100814d2000-07-09 15:48:49 +00001882Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001883{
1884 PyObject *dict;
1885 PyObject *list;
1886 int i;
1887
1888 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001889 if (dict == NULL)
1890 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001891 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001892 if (list == NULL || !PyList_Check(list))
1893 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001894 i = PyList_GET_SIZE(list);
1895 /* Count backwards because we always expect obj to be list[-1] */
1896 while (--i >= 0) {
1897 if (PyList_GET_ITEM(list, i) == obj) {
1898 PyList_SetSlice(list, i, i + 1, NULL);
1899 break;
1900 }
1901 }
1902}
Guido van Rossumd724b232000-03-13 16:01:29 +00001903
1904/*
1905 trashcan
1906 CT 2k0130
1907 non-recursively destroy nested objects
1908
1909 CT 2k0223
1910 everything is now done in a macro.
1911
1912 CT 2k0305
1913 modified to use functions, after Tim Peter's suggestion.
1914
1915 CT 2k0309
1916 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001917
1918 CT 2k0325
1919 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00001920
1921 CT 2k0422
1922 complete rewrite. We now build a chain via ob_type
1923 and save the limited number of types in ob_refcnt.
1924 This is perfect since we don't need any memory.
1925 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00001926*/
1927
Guido van Rossume92e6102000-04-24 15:40:53 +00001928#define Py_TRASHCAN_TUPLE 1
1929#define Py_TRASHCAN_LIST 2
1930#define Py_TRASHCAN_DICT 3
1931#define Py_TRASHCAN_FRAME 4
1932#define Py_TRASHCAN_TRACEBACK 5
1933/* extend here if other objects want protection */
1934
Guido van Rossumd724b232000-03-13 16:01:29 +00001935int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001936
Guido van Rossumd724b232000-03-13 16:01:29 +00001937PyObject * _PyTrash_delete_later = NULL;
1938
1939void
Fred Drake100814d2000-07-09 15:48:49 +00001940_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001941{
Guido van Rossume92e6102000-04-24 15:40:53 +00001942 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001943
Guido van Rossume92e6102000-04-24 15:40:53 +00001944 if (PyTuple_Check(op))
1945 typecode = Py_TRASHCAN_TUPLE;
1946 else if (PyList_Check(op))
1947 typecode = Py_TRASHCAN_LIST;
1948 else if (PyDict_Check(op))
1949 typecode = Py_TRASHCAN_DICT;
1950 else if (PyFrame_Check(op))
1951 typecode = Py_TRASHCAN_FRAME;
1952 else if (PyTraceBack_Check(op))
1953 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00001954 else /* We have a bug here -- those are the only types in GC */ {
1955 Py_FatalError("Type not supported in GC -- internal bug");
1956 return; /* pacify compiler -- execution never here */
1957 }
Guido van Rossume92e6102000-04-24 15:40:53 +00001958 op->ob_refcnt = typecode;
Guido van Rossumd724b232000-03-13 16:01:29 +00001959
Guido van Rossume92e6102000-04-24 15:40:53 +00001960 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
1961 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001962}
1963
1964void
Fred Drake100814d2000-07-09 15:48:49 +00001965_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001966{
1967 while (_PyTrash_delete_later) {
1968 PyObject *shredder = _PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001969 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
1970
1971 switch (shredder->ob_refcnt) {
1972 case Py_TRASHCAN_TUPLE:
1973 shredder->ob_type = &PyTuple_Type;
1974 break;
1975 case Py_TRASHCAN_LIST:
1976 shredder->ob_type = &PyList_Type;
1977 break;
1978 case Py_TRASHCAN_DICT:
1979 shredder->ob_type = &PyDict_Type;
1980 break;
1981 case Py_TRASHCAN_FRAME:
1982 shredder->ob_type = &PyFrame_Type;
1983 break;
1984 case Py_TRASHCAN_TRACEBACK:
1985 shredder->ob_type = &PyTraceBack_Type;
1986 break;
1987 }
1988 _Py_NewReference(shredder);
1989
Guido van Rossumd724b232000-03-13 16:01:29 +00001990 ++_PyTrash_delete_nesting;
1991 Py_DECREF(shredder);
1992 --_PyTrash_delete_nesting;
1993 }
1994}
Neil Schemenauera35c6882001-02-27 04:45:05 +00001995
1996#ifdef WITH_PYMALLOC
1997#include "obmalloc.c"
1998#endif