blob: 5c2dcf5b1668d0d6c95a756c6f553dcfc2f29be8 [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 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000264 if (v->ob_type->tp_str == NULL)
265 return PyObject_Repr(v);
266
267 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000268 if (res == NULL)
269 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000270#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000271 if (PyUnicode_Check(res)) {
272 PyObject* str;
273 str = PyUnicode_AsEncodedString(res, NULL, NULL);
274 Py_DECREF(res);
275 if (str)
276 res = str;
277 else
278 return NULL;
279 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000280#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000281 if (!PyString_Check(res)) {
282 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000283 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000284 res->ob_type->tp_name);
285 Py_DECREF(res);
286 return NULL;
287 }
288 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000289}
290
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000291#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000292PyObject *
293PyObject_Unicode(PyObject *v)
294{
295 PyObject *res;
296
297 if (v == NULL)
298 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000299 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000300 Py_INCREF(v);
301 return v;
302 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000303 if (PyUnicode_Check(v)) {
304 /* For a Unicode subtype that's not a Unicode object,
305 return a true Unicode object with the same data. */
306 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
307 PyUnicode_GET_SIZE(v));
308 }
309 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000310 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 {
314 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000315 static PyObject *unicodestr;
316 /* XXX As soon as we have a tp_unicode slot, we should
317 check this before trying the __unicode__
318 method. */
319 if (unicodestr == NULL) {
320 unicodestr= PyString_InternFromString(
321 "__unicode__");
322 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000323 return NULL;
324 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000325 func = PyObject_GetAttr(v, unicodestr);
326 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000327 res = PyEval_CallObject(func, (PyObject *)NULL);
328 Py_DECREF(func);
329 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000330 else {
331 PyErr_Clear();
332 if (v->ob_type->tp_str != NULL)
333 res = (*v->ob_type->tp_str)(v);
334 else
335 res = PyObject_Repr(v);
336 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000337 }
338 if (res == NULL)
339 return NULL;
340 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000341 PyObject *str;
342 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000343 Py_DECREF(res);
344 if (str)
345 res = str;
346 else
347 return NULL;
348 }
349 return res;
350}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000351#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000352
353
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000354/* Macro to get the tp_richcompare field of a type if defined */
355#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
356 ? (t)->tp_richcompare : NULL)
357
Guido van Rossume797ec12001-01-17 15:24:28 +0000358/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
359static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000360
Guido van Rossume797ec12001-01-17 15:24:28 +0000361/* Try a genuine rich comparison, returning an object. Return:
362 NULL for exception;
363 NotImplemented if this particular rich comparison is not implemented or
364 undefined;
365 some object not equal to NotImplemented if it is implemented
366 (this latter object may not be a Boolean).
367*/
368static PyObject *
369try_rich_compare(PyObject *v, PyObject *w, int op)
370{
371 richcmpfunc f;
372 PyObject *res;
373
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000374 if (v->ob_type != w->ob_type &&
375 PyType_IsSubtype(w->ob_type, v->ob_type) &&
376 (f = RICHCOMPARE(w->ob_type)) != NULL) {
377 res = (*f)(w, v, swapped_op[op]);
378 if (res != Py_NotImplemented)
379 return res;
380 Py_DECREF(res);
381 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000382 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000383 res = (*f)(v, w, op);
384 if (res != Py_NotImplemented)
385 return res;
386 Py_DECREF(res);
387 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000388 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000389 return (*f)(w, v, swapped_op[op]);
390 }
391 res = Py_NotImplemented;
392 Py_INCREF(res);
393 return res;
394}
395
396/* Try a genuine rich comparison, returning an int. Return:
397 -1 for exception (including the case where try_rich_compare() returns an
398 object that's not a Boolean);
399 0 if the outcome is false;
400 1 if the outcome is true;
401 2 if this particular rich comparison is not implemented or undefined.
402*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000403static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000404try_rich_compare_bool(PyObject *v, PyObject *w, int op)
405{
406 PyObject *res;
407 int ok;
408
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000409 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000410 return 2; /* Shortcut, avoid INCREF+DECREF */
411 res = try_rich_compare(v, w, op);
412 if (res == NULL)
413 return -1;
414 if (res == Py_NotImplemented) {
415 Py_DECREF(res);
416 return 2;
417 }
418 ok = PyObject_IsTrue(res);
419 Py_DECREF(res);
420 return ok;
421}
422
423/* Try rich comparisons to determine a 3-way comparison. Return:
424 -2 for an exception;
425 -1 if v < w;
426 0 if v == w;
427 1 if v > w;
428 2 if this particular rich comparison is not implemented or undefined.
429*/
430static int
431try_rich_to_3way_compare(PyObject *v, PyObject *w)
432{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000433 static struct { int op; int outcome; } tries[3] = {
434 /* Try this operator, and if it is true, use this outcome: */
435 {Py_EQ, 0},
436 {Py_LT, -1},
437 {Py_GT, 1},
438 };
439 int i;
440
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000441 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000442 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000443
444 for (i = 0; i < 3; i++) {
445 switch (try_rich_compare_bool(v, w, tries[i].op)) {
446 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000447 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000448 case 1:
449 return tries[i].outcome;
450 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000451 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000452
453 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000454}
455
456/* Try a 3-way comparison, returning an int. Return:
457 -2 for an exception;
458 -1 if v < w;
459 0 if v == w;
460 1 if v > w;
461 2 if this particular 3-way comparison is not implemented or undefined.
462*/
463static int
464try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000465{
466 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000467 cmpfunc f;
468
469 /* Comparisons involving instances are given to instance_compare,
470 which has the same return conventions as this function. */
471
Guido van Rossumab3b0342001-09-18 20:38:53 +0000472 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000473 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000474 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000475 if (PyInstance_Check(w))
476 return (*w->ob_type->tp_compare)(v, w);
477
Guido van Rossumab3b0342001-09-18 20:38:53 +0000478 /* If both have the same (non-NULL) tp_compare, use it. */
479 if (f != NULL && f == w->ob_type->tp_compare) {
480 c = (*f)(v, w);
481 if (c < 0 && PyErr_Occurred())
482 return -1;
483 return c < 0 ? -1 : c > 0 ? 1 : 0;
484 }
485
486 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
487 if (f == _PyObject_SlotCompare ||
488 w->ob_type->tp_compare == _PyObject_SlotCompare)
489 return _PyObject_SlotCompare(v, w);
490
Guido van Rossume797ec12001-01-17 15:24:28 +0000491 /* Try coercion; if it fails, give up */
492 c = PyNumber_CoerceEx(&v, &w);
493 if (c < 0)
494 return -2;
495 if (c > 0)
496 return 2;
497
498 /* Try v's comparison, if defined */
499 if ((f = v->ob_type->tp_compare) != NULL) {
500 c = (*f)(v, w);
501 Py_DECREF(v);
502 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000503 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000504 return -2;
505 return c < 0 ? -1 : c > 0 ? 1 : 0;
506 }
507
508 /* Try w's comparison, if defined */
509 if ((f = w->ob_type->tp_compare) != NULL) {
510 c = (*f)(w, v); /* swapped! */
511 Py_DECREF(v);
512 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000513 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000514 return -2;
515 return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
516 }
517
518 /* No comparison defined */
519 Py_DECREF(v);
520 Py_DECREF(w);
521 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000522}
523
Guido van Rossume797ec12001-01-17 15:24:28 +0000524/* Final fallback 3-way comparison, returning an int. Return:
525 -2 if an error occurred;
526 -1 if v < w;
527 0 if v == w;
528 1 if v > w.
529*/
530static int
531default_3way_compare(PyObject *v, PyObject *w)
532{
533 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000534 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000535
536 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000537 /* When comparing these pointers, they must be cast to
538 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
539 * uintptr_t). ANSI specifies that pointer compares other
540 * than == and != to non-related structures are undefined.
541 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000542 Py_uintptr_t vv = (Py_uintptr_t)v;
543 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000544 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
545 }
546
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000547#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000548 /* Special case for Unicode */
549 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
550 c = PyUnicode_Compare(v, w);
551 if (!PyErr_Occurred())
552 return c;
553 /* TypeErrors are ignored: if Unicode coercion fails due
554 to one of the arguments not having the right type, we
555 continue as defined by the coercion protocol (see
556 above). Luckily, decoding errors are reported as
557 ValueErrors and are not masked by this technique. */
558 if (!PyErr_ExceptionMatches(PyExc_TypeError))
559 return -2;
560 PyErr_Clear();
561 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000562#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000563
Guido van Rossum0871e932001-01-22 19:28:09 +0000564 /* None is smaller than anything */
565 if (v == Py_None)
566 return -1;
567 if (w == Py_None)
568 return 1;
569
Guido van Rossume797ec12001-01-17 15:24:28 +0000570 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000571 if (v->ob_type->tp_as_number)
572 vname = "";
573 else
574 vname = v->ob_type->tp_name;
575 if (w->ob_type->tp_as_number)
576 wname = "";
577 else
578 wname = w->ob_type->tp_name;
579 c = strcmp(vname, wname);
580 if (c < 0)
581 return -1;
582 if (c > 0)
583 return 1;
584 /* Same type name, or (more likely) incomparable numeric types */
585 return ((Py_uintptr_t)(v->ob_type) < (
586 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000587}
588
589#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
590
Tim Peters6d60b2e2001-05-07 20:53:51 +0000591/* Do a 3-way comparison, by hook or by crook. Return:
592 -2 for an exception;
593 -1 if v < w;
594 0 if v == w;
595 1 if v > w;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000596 If the object implements a tp_compare function, it returns
597 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000598*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000599static int
Fred Drake100814d2000-07-09 15:48:49 +0000600do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000601{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000602 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000603 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000604
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000605 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000606 && (f = v->ob_type->tp_compare) != NULL) {
607 c = (*f)(v, w);
608 if (c != 2 || !PyInstance_Check(v))
609 return c;
610 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000611 c = try_rich_to_3way_compare(v, w);
612 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000613 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000614 c = try_3way_compare(v, w);
615 if (c < 2)
616 return c;
617 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000618}
619
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000620/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000621 some types) and decremented on exit. If the count exceeds the
622 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000623
624 This is a tunable parameter that should only affect the performance
625 of comparisons, nothing else. Setting it high makes comparing deeply
626 nested non-cyclical data structures faster, but makes comparing cyclical
627 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000628*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000629#define NESTING_LIMIT 20
630
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000631static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000632
633static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000634get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000635{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000636 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000637 PyObject *tstate_dict, *inprogress;
638
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000639 if (key == NULL) {
640 key = PyString_InternFromString("cmp_state");
641 if (key == NULL)
642 return NULL;
643 }
644
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000645 tstate_dict = PyThreadState_GetDict();
646 if (tstate_dict == NULL) {
647 PyErr_BadInternalCall();
648 return NULL;
649 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000650
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000651 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000652 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000653 inprogress = PyDict_New();
654 if (inprogress == NULL)
655 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000656 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000657 Py_DECREF(inprogress);
658 return NULL;
659 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000660 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000661 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000662
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000663 return inprogress;
664}
665
666static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000667check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000668{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000669 PyObject *inprogress;
670 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000671 Py_uintptr_t iv = (Py_uintptr_t)v;
672 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000673 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000674
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000675 inprogress = get_inprogress_dict();
676 if (inprogress == NULL)
677 return NULL;
678
679 token = PyTuple_New(3);
680 if (token == NULL)
681 return NULL;
682
683 if (iv <= iw) {
684 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
685 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
686 if (op >= 0)
687 op = swapped_op[op];
688 } else {
689 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
690 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
691 }
692 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
693 if (x == NULL || y == NULL || z == NULL) {
694 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000695 return NULL;
696 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000697
698 if (PyDict_GetItem(inprogress, token) != NULL) {
699 Py_DECREF(token);
700 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000701 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000702
703 if (PyDict_SetItem(inprogress, token, token) < 0) {
704 Py_DECREF(token);
705 return NULL;
706 }
707
708 return token;
709}
710
711static void
712delete_token(PyObject *token)
713{
714 PyObject *inprogress;
715
716 if (token == NULL || token == Py_None)
717 return;
718 inprogress = get_inprogress_dict();
719 if (inprogress == NULL)
720 PyErr_Clear();
721 else
722 PyDict_DelItem(inprogress, token);
723 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000724}
725
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726int
Fred Drake100814d2000-07-09 15:48:49 +0000727PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000729 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000730 int result;
731
Jack Jansend49cbe12000-08-22 21:52:51 +0000732#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000733 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000734 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000735 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000736 }
737#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000738 if (v == NULL || w == NULL) {
739 PyErr_BadInternalCall();
740 return -1;
741 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000742 if (v == w)
743 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000744 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000745 compare_nesting++;
746 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000747 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000748 || (vtp->tp_as_sequence
749 && !PyString_Check(v)
750 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000751 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000752 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000753
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000754 if (token == NULL) {
755 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000756 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000757 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000758 /* already comparing these objects. assume
759 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000760 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000761 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000762 else {
763 result = do_cmp(v, w);
764 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000765 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000766 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000767 else {
768 result = do_cmp(v, w);
769 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000770 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000771 return result < 0 ? -1 : result;
772}
773
774static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000775convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000776{
Guido van Rossume797ec12001-01-17 15:24:28 +0000777 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000778 switch (op) {
779 case Py_LT: c = c < 0; break;
780 case Py_LE: c = c <= 0; break;
781 case Py_EQ: c = c == 0; break;
782 case Py_NE: c = c != 0; break;
783 case Py_GT: c = c > 0; break;
784 case Py_GE: c = c >= 0; break;
785 }
786 result = c ? Py_True : Py_False;
787 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000788 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000789}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000790
791
792static PyObject *
793try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
794{
795 int c;
796
797 c = try_3way_compare(v, w);
798 if (c >= 2)
799 c = default_3way_compare(v, w);
800 if (c <= -2)
801 return NULL;
802 return convert_3way_to_object(op, c);
803}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000805static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000806do_richcmp(PyObject *v, PyObject *w, int op)
807{
808 PyObject *res;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000809 cmpfunc f;
810
811 /* If the types are equal, don't bother with coercions etc.
812 Instances are special-cased in try_3way_compare, since
813 a result of 2 does *not* mean one value being greater
814 than the other. */
815 if (v->ob_type == w->ob_type
816 && (f = v->ob_type->tp_compare) != NULL
817 && !PyInstance_Check(v)) {
818 int c;
819 richcmpfunc f1;
820 if ((f1 = RICHCOMPARE(v->ob_type)) != NULL) {
821 /* If the type has richcmp, try it first.
822 try_rich_compare would try it two-sided,
823 which is not needed since we've a single
824 type only. */
825 res = (*f1)(v, w, op);
826 if (res != Py_NotImplemented)
827 return res;
828 Py_DECREF(res);
829 }
830 c = (*f)(v, w);
831 if (c < 0 && PyErr_Occurred())
832 return NULL;
833 return convert_3way_to_object(op, c);
834 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000835
836 res = try_rich_compare(v, w, op);
837 if (res != Py_NotImplemented)
838 return res;
839 Py_DECREF(res);
840
841 return try_3way_to_rich_compare(v, w, op);
842}
843
844PyObject *
845PyObject_RichCompare(PyObject *v, PyObject *w, int op)
846{
847 PyObject *res;
848
849 assert(Py_LT <= op && op <= Py_GE);
850
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000851 compare_nesting++;
852 if (compare_nesting > NESTING_LIMIT &&
853 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000854 || (v->ob_type->tp_as_sequence
855 && !PyString_Check(v)
856 && !PyTuple_Check(v)))) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000857 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000858 PyObject *token = check_recursion(v, w, op);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000859
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000860 if (token == NULL) {
861 res = NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000862 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000863 else if (token == Py_None) {
864 /* already comparing these objects with this operator.
865 assume they're equal until shown otherwise */
866 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000867 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000868 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000869 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000870 else {
871 PyErr_SetString(PyExc_ValueError,
872 "can't order recursive values");
873 res = NULL;
874 }
875 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000876 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000877 else {
878 res = do_richcmp(v, w, op);
879 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000880 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000881 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000882 else {
883 res = do_richcmp(v, w, op);
884 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000885 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000886 return res;
887}
888
Tim Petersde9725f2001-05-05 10:06:17 +0000889/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000890int
891PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
892{
893 PyObject *res = PyObject_RichCompare(v, w, op);
894 int ok;
895
896 if (res == NULL)
897 return -1;
898 ok = PyObject_IsTrue(res);
899 Py_DECREF(res);
900 return ok;
901}
Fred Drake13634cf2000-06-29 19:17:04 +0000902
903/* Set of hash utility functions to help maintaining the invariant that
904 iff a==b then hash(a)==hash(b)
905
906 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
907*/
908
909long
Fred Drake100814d2000-07-09 15:48:49 +0000910_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000911{
Tim Peters39dce292000-08-15 03:34:48 +0000912 double intpart, fractpart;
913 int expo;
914 long hipart;
915 long x; /* the final hash value */
916 /* This is designed so that Python numbers of different types
917 * that compare equal hash to the same value; otherwise comparisons
918 * of mapping keys will turn out weird.
919 */
920
921#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
922{
923 extended e;
924 fractpart = modf(v, &e);
925 intpart = e;
926}
927#else
928 fractpart = modf(v, &intpart);
929#endif
930 if (fractpart == 0.0) {
931 /* This must return the same hash as an equal int or long. */
932 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
933 /* Convert to long and use its hash. */
934 PyObject *plong; /* converted to Python long */
935 if (Py_IS_INFINITY(intpart))
936 /* can't convert to long int -- arbitrary */
937 v = v < 0 ? -271828.0 : 314159.0;
938 plong = PyLong_FromDouble(v);
939 if (plong == NULL)
940 return -1;
941 x = PyObject_Hash(plong);
942 Py_DECREF(plong);
943 return x;
944 }
945 /* Fits in a C long == a Python int, so is its own hash. */
946 x = (long)intpart;
947 if (x == -1)
948 x = -2;
949 return x;
950 }
951 /* The fractional part is non-zero, so we don't have to worry about
952 * making this match the hash of some other type.
953 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000954 * Since the VAX D double format has 56 mantissa bits, which is the
955 * most of any double format in use, each of these parts may have as
956 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000957 * So, assuming sizeof(long) >= 4, each part can be broken into two
958 * longs; frexp and multiplication are used to do that.
959 * Also, since the Cray double format has 15 exponent bits, which is
960 * the most of any double format in use, shifting the exponent field
961 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000962 */
Tim Peters39dce292000-08-15 03:34:48 +0000963 v = frexp(v, &expo);
964 v *= 2147483648.0; /* 2**31 */
965 hipart = (long)v; /* take the top 32 bits */
966 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
967 x = hipart + (long)v + (expo << 15);
968 if (x == -1)
969 x = -2;
970 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000971}
972
973long
Fred Drake100814d2000-07-09 15:48:49 +0000974_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000975{
976#if SIZEOF_LONG >= SIZEOF_VOID_P
977 return (long)p;
978#else
979 /* convert to a Python long and hash that */
980 PyObject* longobj;
981 long x;
982
983 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
984 x = -1;
985 goto finally;
986 }
987 x = PyObject_Hash(longobj);
988
989finally:
990 Py_XDECREF(longobj);
991 return x;
992#endif
993}
994
995
Guido van Rossum9bfef441993-03-29 10:43:31 +0000996long
Fred Drake100814d2000-07-09 15:48:49 +0000997PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000998{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000999 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001000 if (tp->tp_hash != NULL)
1001 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001002 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001003 return _Py_HashPointer(v); /* Use address as hash value */
1004 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001005 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001006 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001007 return -1;
1008}
1009
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001010PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001011PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001012{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001014
Tim Peters6d6c1a32001-08-02 04:15:00 +00001015 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001016 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001017 w = PyString_InternFromString(name);
1018 if (w == NULL)
1019 return NULL;
1020 res = PyObject_GetAttr(v, w);
1021 Py_XDECREF(w);
1022 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001023}
1024
1025int
Fred Drake100814d2000-07-09 15:48:49 +00001026PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001027{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001028 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001029 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001030 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001031 return 1;
1032 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001033 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001034 return 0;
1035}
1036
1037int
Fred Drake100814d2000-07-09 15:48:49 +00001038PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001039{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001040 PyObject *s;
1041 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001042
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001044 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045 s = PyString_InternFromString(name);
1046 if (s == NULL)
1047 return -1;
1048 res = PyObject_SetAttr(v, s, w);
1049 Py_XDECREF(s);
1050 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001051}
1052
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001053PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001054PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001055{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056 PyTypeObject *tp = v->ob_type;
1057
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001058#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001059 /* The Unicode to string conversion is done here because the
1060 existing tp_getattro slots expect a string object as name
1061 and we wouldn't want to break those. */
1062 if (PyUnicode_Check(name)) {
1063 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1064 if (name == NULL)
1065 return NULL;
1066 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001067#endif
1068
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001069 if (!PyString_Check(name)) {
1070 PyErr_SetString(PyExc_TypeError,
1071 "attribute name must be string");
1072 return NULL;
1073 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074 if (tp->tp_getattro != NULL)
1075 return (*tp->tp_getattro)(v, name);
1076 if (tp->tp_getattr != NULL)
1077 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1078 PyErr_Format(PyExc_AttributeError,
1079 "'%.50s' object has no attribute '%.400s'",
1080 tp->tp_name, PyString_AS_STRING(name));
1081 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001082}
1083
1084int
Fred Drake100814d2000-07-09 15:48:49 +00001085PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001086{
1087 PyObject *res = PyObject_GetAttr(v, name);
1088 if (res != NULL) {
1089 Py_DECREF(res);
1090 return 1;
1091 }
1092 PyErr_Clear();
1093 return 0;
1094}
1095
1096int
Fred Drake100814d2000-07-09 15:48:49 +00001097PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001098{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001100 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001101
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001102#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001103 /* The Unicode to string conversion is done here because the
1104 existing tp_setattro slots expect a string object as name
1105 and we wouldn't want to break those. */
1106 if (PyUnicode_Check(name)) {
1107 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1108 if (name == NULL)
1109 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001110 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001111 else
1112#endif
1113 if (!PyString_Check(name)){
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001114 PyErr_SetString(PyExc_TypeError,
1115 "attribute name must be string");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118 else
1119 Py_INCREF(name);
1120
1121 PyString_InternInPlace(&name);
1122 if (tp->tp_setattro != NULL) {
1123 err = (*tp->tp_setattro)(v, name, value);
1124 Py_DECREF(name);
1125 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001126 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 if (tp->tp_setattr != NULL) {
1128 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1129 Py_DECREF(name);
1130 return err;
1131 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001132 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1134 PyErr_Format(PyExc_TypeError,
1135 "'%.100s' object has no attributes "
1136 "(%s .%.100s)",
1137 tp->tp_name,
1138 value==NULL ? "del" : "assign to",
1139 PyString_AS_STRING(name));
1140 else
1141 PyErr_Format(PyExc_TypeError,
1142 "'%.100s' object has only read-only attributes "
1143 "(%s .%.100s)",
1144 tp->tp_name,
1145 value==NULL ? "del" : "assign to",
1146 PyString_AS_STRING(name));
1147 return -1;
1148}
1149
1150/* Helper to get a pointer to an object's __dict__ slot, if any */
1151
1152PyObject **
1153_PyObject_GetDictPtr(PyObject *obj)
1154{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 long dictoffset;
1156 PyTypeObject *tp = obj->ob_type;
1157
1158 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1159 return NULL;
1160 dictoffset = tp->tp_dictoffset;
1161 if (dictoffset == 0)
1162 return NULL;
1163 if (dictoffset < 0) {
Tim Petersf2a67da2001-10-07 03:54:51 +00001164 const size_t size = _PyObject_VAR_SIZE(tp,
1165 ((PyVarObject *)obj)->ob_size);
Tim Peters6d483d32001-10-06 21:27:34 +00001166 dictoffset += (long)size;
1167 assert(dictoffset > 0);
1168 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 }
1170 return (PyObject **) ((char *)obj + dictoffset);
1171}
1172
1173/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1174
1175PyObject *
1176PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1177{
1178 PyTypeObject *tp = obj->ob_type;
1179 PyObject *descr;
1180 descrgetfunc f;
1181 PyObject **dictptr;
1182
1183 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001184 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185 return NULL;
1186 }
1187
1188 descr = _PyType_Lookup(tp, name);
1189 f = NULL;
1190 if (descr != NULL) {
1191 f = descr->ob_type->tp_descr_get;
1192 if (f != NULL && PyDescr_IsData(descr))
1193 return f(descr, obj, (PyObject *)obj->ob_type);
1194 }
1195
1196 dictptr = _PyObject_GetDictPtr(obj);
1197 if (dictptr != NULL) {
1198 PyObject *dict = *dictptr;
1199 if (dict != NULL) {
1200 PyObject *res = PyDict_GetItem(dict, name);
1201 if (res != NULL) {
1202 Py_INCREF(res);
1203 return res;
1204 }
1205 }
1206 }
1207
1208 if (f != NULL)
1209 return f(descr, obj, (PyObject *)obj->ob_type);
1210
1211 if (descr != NULL) {
1212 Py_INCREF(descr);
1213 return descr;
1214 }
1215
1216 PyErr_Format(PyExc_AttributeError,
1217 "'%.50s' object has no attribute '%.400s'",
1218 tp->tp_name, PyString_AS_STRING(name));
1219 return NULL;
1220}
1221
1222int
1223PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1224{
1225 PyTypeObject *tp = obj->ob_type;
1226 PyObject *descr;
1227 descrsetfunc f;
1228 PyObject **dictptr;
1229
1230 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001231 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 return -1;
1233 }
1234
1235 descr = _PyType_Lookup(tp, name);
1236 f = NULL;
1237 if (descr != NULL) {
1238 f = descr->ob_type->tp_descr_set;
1239 if (f != NULL && PyDescr_IsData(descr))
1240 return f(descr, obj, value);
1241 }
1242
1243 dictptr = _PyObject_GetDictPtr(obj);
1244 if (dictptr != NULL) {
1245 PyObject *dict = *dictptr;
1246 if (dict == NULL && value != NULL) {
1247 dict = PyDict_New();
1248 if (dict == NULL)
1249 return -1;
1250 *dictptr = dict;
1251 }
1252 if (dict != NULL) {
1253 int res;
1254 if (value == NULL)
1255 res = PyDict_DelItem(dict, name);
1256 else
1257 res = PyDict_SetItem(dict, name, value);
1258 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1259 PyErr_SetObject(PyExc_AttributeError, name);
1260 return res;
1261 }
1262 }
1263
1264 if (f != NULL)
1265 return f(descr, obj, value);
1266
1267 if (descr == NULL) {
1268 PyErr_Format(PyExc_AttributeError,
1269 "'%.50s' object has no attribute '%.400s'",
1270 tp->tp_name, PyString_AS_STRING(name));
1271 return -1;
1272 }
1273
1274 PyErr_Format(PyExc_AttributeError,
1275 "'%.50s' object attribute '%.400s' is read-only",
1276 tp->tp_name, PyString_AS_STRING(name));
1277 return -1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001278}
1279
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001280/* Test a value used as condition, e.g., in a for or if statement.
1281 Return -1 if an error occurred */
1282
1283int
Fred Drake100814d2000-07-09 15:48:49 +00001284PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001285{
1286 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001287 if (v == Py_None)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001288 res = 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001289 else if (v->ob_type->tp_as_number != NULL &&
1290 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001291 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001292 else if (v->ob_type->tp_as_mapping != NULL &&
1293 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001294 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001295 else if (v->ob_type->tp_as_sequence != NULL &&
1296 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001297 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1298 else
1299 res = 1;
1300 if (res > 0)
1301 res = 1;
1302 return res;
1303}
1304
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001305/* equivalent of 'not v'
1306 Return -1 if an error occurred */
1307
1308int
Fred Drake100814d2000-07-09 15:48:49 +00001309PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001310{
1311 int res;
1312 res = PyObject_IsTrue(v);
1313 if (res < 0)
1314 return res;
1315 return res == 0;
1316}
1317
Guido van Rossum5524a591995-01-10 15:26:20 +00001318/* Coerce two numeric types to the "larger" one.
1319 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001320 Return value:
1321 -1 if an error occurred;
1322 0 if the coercion succeeded (and then the reference counts are increased);
1323 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001324*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001325int
Fred Drake100814d2000-07-09 15:48:49 +00001326PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001327{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001328 register PyObject *v = *pv;
1329 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001330 int res;
1331
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001332 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1333 Py_INCREF(v);
1334 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001335 return 0;
1336 }
1337 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1338 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1339 if (res <= 0)
1340 return res;
1341 }
1342 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1343 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1344 if (res <= 0)
1345 return res;
1346 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001347 return 1;
1348}
1349
Guido van Rossume797ec12001-01-17 15:24:28 +00001350/* Coerce two numeric types to the "larger" one.
1351 Increment the reference count on each argument.
1352 Return -1 and raise an exception if no coercion is possible
1353 (and then no reference count is incremented).
1354*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001355int
Fred Drake100814d2000-07-09 15:48:49 +00001356PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001357{
1358 int err = PyNumber_CoerceEx(pv, pw);
1359 if (err <= 0)
1360 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001361 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001362 return -1;
1363}
1364
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001365
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001366/* Test whether an object can be called */
1367
1368int
Fred Drake100814d2000-07-09 15:48:49 +00001369PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001370{
1371 if (x == NULL)
1372 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373 if (PyInstance_Check(x)) {
1374 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001375 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001377 return 0;
1378 }
1379 /* Could test recursively but don't, for fear of endless
1380 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001381 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001382 return 1;
1383 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384 else {
1385 return x->ob_type->tp_call != NULL;
1386 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001387}
1388
Tim Peters7eea37e2001-09-04 22:08:56 +00001389/* Helper for PyObject_Dir.
1390 Merge the __dict__ of aclass into dict, and recursively also all
1391 the __dict__s of aclass's base classes. The order of merging isn't
1392 defined, as it's expected that only the final set of dict keys is
1393 interesting.
1394 Return 0 on success, -1 on error.
1395*/
1396
1397static int
1398merge_class_dict(PyObject* dict, PyObject* aclass)
1399{
1400 PyObject *classdict;
1401 PyObject *bases;
1402
1403 assert(PyDict_Check(dict));
1404 assert(aclass);
1405
1406 /* Merge in the type's dict (if any). */
1407 classdict = PyObject_GetAttrString(aclass, "__dict__");
1408 if (classdict == NULL)
1409 PyErr_Clear();
1410 else {
1411 int status = PyDict_Update(dict, classdict);
1412 Py_DECREF(classdict);
1413 if (status < 0)
1414 return -1;
1415 }
1416
1417 /* Recursively merge in the base types' (if any) dicts. */
1418 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001419 if (bases == NULL)
1420 PyErr_Clear();
1421 else {
Tim Peters7eea37e2001-09-04 22:08:56 +00001422 int i, n;
1423 assert(PyTuple_Check(bases));
1424 n = PyTuple_GET_SIZE(bases);
1425 for (i = 0; i < n; i++) {
1426 PyObject *base = PyTuple_GET_ITEM(bases, i);
1427 if (merge_class_dict(dict, base) < 0) {
1428 Py_DECREF(bases);
1429 return -1;
1430 }
1431 }
1432 Py_DECREF(bases);
1433 }
1434 return 0;
1435}
1436
Tim Peters305b5852001-09-17 02:38:46 +00001437/* Helper for PyObject_Dir.
1438 If obj has an attr named attrname that's a list, merge its string
1439 elements into keys of dict.
1440 Return 0 on success, -1 on error. Errors due to not finding the attr,
1441 or the attr not being a list, are suppressed.
1442*/
1443
1444static int
1445merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1446{
1447 PyObject *list;
1448 int result = 0;
1449
1450 assert(PyDict_Check(dict));
1451 assert(obj);
1452 assert(attrname);
1453
1454 list = PyObject_GetAttrString(obj, attrname);
1455 if (list == NULL)
1456 PyErr_Clear();
1457
1458 else if (PyList_Check(list)) {
1459 int i;
1460 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1461 PyObject *item = PyList_GET_ITEM(list, i);
1462 if (PyString_Check(item)) {
1463 result = PyDict_SetItem(dict, item, Py_None);
1464 if (result < 0)
1465 break;
1466 }
1467 }
1468 }
1469
1470 Py_XDECREF(list);
1471 return result;
1472}
1473
Tim Peters7eea37e2001-09-04 22:08:56 +00001474/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1475 docstring, which should be kept in synch with this implementation. */
1476
1477PyObject *
1478PyObject_Dir(PyObject *arg)
1479{
1480 /* Set exactly one of these non-NULL before the end. */
1481 PyObject *result = NULL; /* result list */
1482 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1483
1484 /* If NULL arg, return the locals. */
1485 if (arg == NULL) {
1486 PyObject *locals = PyEval_GetLocals();
1487 if (locals == NULL)
1488 goto error;
1489 result = PyDict_Keys(locals);
1490 if (result == NULL)
1491 goto error;
1492 }
1493
1494 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001495 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001496 masterdict = PyObject_GetAttrString(arg, "__dict__");
1497 if (masterdict == NULL)
1498 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001499 if (!PyDict_Check(masterdict)) {
1500 PyErr_SetString(PyExc_TypeError,
1501 "module.__dict__ is not a dictionary");
1502 goto error;
1503 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001504 }
1505
1506 /* Elif some form of type or class, grab its dict and its bases.
1507 We deliberately don't suck up its __class__, as methods belonging
1508 to the metaclass would probably be more confusing than helpful. */
1509 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1510 masterdict = PyDict_New();
1511 if (masterdict == NULL)
1512 goto error;
1513 if (merge_class_dict(masterdict, arg) < 0)
1514 goto error;
1515 }
1516
1517 /* Else look at its dict, and the attrs reachable from its class. */
1518 else {
1519 PyObject *itsclass;
1520 /* Create a dict to start with. CAUTION: Not everything
1521 responding to __dict__ returns a dict! */
1522 masterdict = PyObject_GetAttrString(arg, "__dict__");
1523 if (masterdict == NULL) {
1524 PyErr_Clear();
1525 masterdict = PyDict_New();
1526 }
1527 else if (!PyDict_Check(masterdict)) {
1528 Py_DECREF(masterdict);
1529 masterdict = PyDict_New();
1530 }
1531 else {
1532 /* The object may have returned a reference to its
1533 dict, so copy it to avoid mutating it. */
1534 PyObject *temp = PyDict_Copy(masterdict);
1535 Py_DECREF(masterdict);
1536 masterdict = temp;
1537 }
1538 if (masterdict == NULL)
1539 goto error;
1540
Tim Peters305b5852001-09-17 02:38:46 +00001541 /* Merge in __members__ and __methods__ (if any).
1542 XXX Would like this to go away someday; for now, it's
1543 XXX needed to get at im_self etc of method objects. */
1544 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1545 goto error;
1546 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1547 goto error;
1548
Tim Peters7eea37e2001-09-04 22:08:56 +00001549 /* Merge in attrs reachable from its class.
1550 CAUTION: Not all objects have a __class__ attr. */
1551 itsclass = PyObject_GetAttrString(arg, "__class__");
1552 if (itsclass == NULL)
1553 PyErr_Clear();
1554 else {
1555 int status = merge_class_dict(masterdict, itsclass);
1556 Py_DECREF(itsclass);
1557 if (status < 0)
1558 goto error;
1559 }
1560 }
1561
1562 assert((result == NULL) ^ (masterdict == NULL));
1563 if (masterdict != NULL) {
1564 /* The result comes from its keys. */
1565 assert(result == NULL);
1566 result = PyDict_Keys(masterdict);
1567 if (result == NULL)
1568 goto error;
1569 }
1570
1571 assert(result);
1572 if (PyList_Sort(result) != 0)
1573 goto error;
1574 else
1575 goto normal_return;
1576
1577 error:
1578 Py_XDECREF(result);
1579 result = NULL;
1580 /* fall through */
1581 normal_return:
1582 Py_XDECREF(masterdict);
1583 return result;
1584}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001585
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001586/*
1587NoObject is usable as a non-NULL undefined value, used by the macro None.
1588There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001589so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001590(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001591*/
1592
Guido van Rossum0c182a11992-03-27 17:26:13 +00001593/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001594static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001595none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001596{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001597 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001598}
1599
Barry Warsaw9bf16442001-01-23 16:24:35 +00001600/* ARGUSED */
1601static void
1602none_dealloc(PyObject* ignore)
1603{
1604 /* This should never get called, but we also don't want to SEGV if
1605 * we accidently decref None out of existance.
1606 */
1607 abort();
1608}
1609
1610
Guido van Rossumba21a492001-08-16 08:17:26 +00001611static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001612 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001613 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001614 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001615 0,
1616 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001617 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001618 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001619 0, /*tp_getattr*/
1620 0, /*tp_setattr*/
1621 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001622 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001623 0, /*tp_as_number*/
1624 0, /*tp_as_sequence*/
1625 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001626 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001627};
1628
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001629PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001630 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001631};
1632
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001633/* NotImplemented is an object that can be used to signal that an
1634 operation is not implemented for the given type combination. */
1635
1636static PyObject *
1637NotImplemented_repr(PyObject *op)
1638{
1639 return PyString_FromString("NotImplemented");
1640}
1641
1642static PyTypeObject PyNotImplemented_Type = {
1643 PyObject_HEAD_INIT(&PyType_Type)
1644 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001645 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001646 0,
1647 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001648 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001649 0, /*tp_print*/
1650 0, /*tp_getattr*/
1651 0, /*tp_setattr*/
1652 0, /*tp_compare*/
1653 (reprfunc)NotImplemented_repr, /*tp_repr*/
1654 0, /*tp_as_number*/
1655 0, /*tp_as_sequence*/
1656 0, /*tp_as_mapping*/
1657 0, /*tp_hash */
1658};
1659
1660PyObject _Py_NotImplementedStruct = {
1661 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1662};
1663
Guido van Rossumba21a492001-08-16 08:17:26 +00001664void
1665_Py_ReadyTypes(void)
1666{
1667 if (PyType_Ready(&PyType_Type) < 0)
1668 Py_FatalError("Can't initialize 'type'");
1669
1670 if (PyType_Ready(&PyList_Type) < 0)
1671 Py_FatalError("Can't initialize 'list'");
1672
1673 if (PyType_Ready(&PyNone_Type) < 0)
1674 Py_FatalError("Can't initialize type(None)");
1675
1676 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1677 Py_FatalError("Can't initialize type(NotImplemented)");
1678}
1679
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001680
Guido van Rossum84a90321996-05-22 16:34:47 +00001681#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001682
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001683static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001684
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001685void
Fred Drake100814d2000-07-09 15:48:49 +00001686_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001687{
1688 refchain._ob_prev = refchain._ob_next = &refchain;
1689 _Py_RefTotal = 0;
1690}
1691
1692void
Fred Drake100814d2000-07-09 15:48:49 +00001693_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001694{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001695 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001696 op->ob_refcnt = 1;
1697 op->_ob_next = refchain._ob_next;
1698 op->_ob_prev = &refchain;
1699 refchain._ob_next->_ob_prev = op;
1700 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001701#ifdef COUNT_ALLOCS
1702 inc_count(op->ob_type);
1703#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001704}
1705
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001706void
Fred Drake100814d2000-07-09 15:48:49 +00001707_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001708{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001709#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001710 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001711#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001712 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001713 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001714 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001715 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001716 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001717#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001718 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1719 if (p == op)
1720 break;
1721 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001722 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001723 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001724#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001725 op->_ob_next->_ob_prev = op->_ob_prev;
1726 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001727 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001728#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001729 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001730#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001731}
1732
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001733void
Fred Drake100814d2000-07-09 15:48:49 +00001734_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001735{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001736 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001737 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001738 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001739}
1740
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001741void
Fred Drake100814d2000-07-09 15:48:49 +00001742_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001743{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001744 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001745 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001746 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1747 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001748 if (PyObject_Print(op, fp, 0) != 0)
1749 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750 putc('\n', fp);
1751 }
1752}
1753
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001754PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001755_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001756{
1757 int i, n;
1758 PyObject *t = NULL;
1759 PyObject *res, *op;
1760
1761 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1762 return NULL;
1763 op = refchain._ob_next;
1764 res = PyList_New(0);
1765 if (res == NULL)
1766 return NULL;
1767 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1768 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001769 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001770 op = op->_ob_next;
1771 if (op == &refchain)
1772 return res;
1773 }
1774 if (PyList_Append(res, op) < 0) {
1775 Py_DECREF(res);
1776 return NULL;
1777 }
1778 op = op->_ob_next;
1779 }
1780 return res;
1781}
1782
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001783#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001784
1785
1786/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001787PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001788
1789
1790/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001791int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001792
1793
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001794/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001795
Thomas Wouters334fb892000-07-25 12:56:38 +00001796void *
Fred Drake100814d2000-07-09 15:48:49 +00001797PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001798{
1799#if _PyMem_EXTRA > 0
1800 if (nbytes == 0)
1801 nbytes = _PyMem_EXTRA;
1802#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001803 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001804}
1805
Thomas Wouters334fb892000-07-25 12:56:38 +00001806void *
1807PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001808{
1809#if _PyMem_EXTRA > 0
1810 if (nbytes == 0)
1811 nbytes = _PyMem_EXTRA;
1812#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001813 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001814}
1815
1816void
Thomas Wouters334fb892000-07-25 12:56:38 +00001817PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001818{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001819 PyMem_FREE(p);
1820}
1821
1822
1823/* Python's object malloc wrappers (see objimpl.h) */
1824
Thomas Wouters334fb892000-07-25 12:56:38 +00001825void *
Fred Drake100814d2000-07-09 15:48:49 +00001826PyObject_Malloc(size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001827{
1828 return PyObject_MALLOC(nbytes);
1829}
1830
Thomas Wouters334fb892000-07-25 12:56:38 +00001831void *
1832PyObject_Realloc(void *p, size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001833{
1834 return PyObject_REALLOC(p, nbytes);
1835}
1836
1837void
Thomas Wouters334fb892000-07-25 12:56:38 +00001838PyObject_Free(void *p)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001839{
1840 PyObject_FREE(p);
Guido van Rossume09fb551997-08-05 02:04:34 +00001841}
Guido van Rossum86610361998-04-10 22:32:46 +00001842
1843
1844/* These methods are used to control infinite recursion in repr, str, print,
1845 etc. Container objects that may recursively contain themselves,
1846 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1847 Py_ReprLeave() to avoid infinite recursion.
1848
1849 Py_ReprEnter() returns 0 the first time it is called for a particular
1850 object and 1 every time thereafter. It returns -1 if an exception
1851 occurred. Py_ReprLeave() has no return value.
1852
1853 See dictobject.c and listobject.c for examples of use.
1854*/
1855
1856#define KEY "Py_Repr"
1857
1858int
Fred Drake100814d2000-07-09 15:48:49 +00001859Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001860{
1861 PyObject *dict;
1862 PyObject *list;
1863 int i;
1864
1865 dict = PyThreadState_GetDict();
1866 if (dict == NULL)
1867 return -1;
1868 list = PyDict_GetItemString(dict, KEY);
1869 if (list == NULL) {
1870 list = PyList_New(0);
1871 if (list == NULL)
1872 return -1;
1873 if (PyDict_SetItemString(dict, KEY, list) < 0)
1874 return -1;
1875 Py_DECREF(list);
1876 }
1877 i = PyList_GET_SIZE(list);
1878 while (--i >= 0) {
1879 if (PyList_GET_ITEM(list, i) == obj)
1880 return 1;
1881 }
1882 PyList_Append(list, obj);
1883 return 0;
1884}
1885
1886void
Fred Drake100814d2000-07-09 15:48:49 +00001887Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001888{
1889 PyObject *dict;
1890 PyObject *list;
1891 int i;
1892
1893 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001894 if (dict == NULL)
1895 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001896 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001897 if (list == NULL || !PyList_Check(list))
1898 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001899 i = PyList_GET_SIZE(list);
1900 /* Count backwards because we always expect obj to be list[-1] */
1901 while (--i >= 0) {
1902 if (PyList_GET_ITEM(list, i) == obj) {
1903 PyList_SetSlice(list, i, i + 1, NULL);
1904 break;
1905 }
1906 }
1907}
Guido van Rossumd724b232000-03-13 16:01:29 +00001908
1909/*
1910 trashcan
1911 CT 2k0130
1912 non-recursively destroy nested objects
1913
1914 CT 2k0223
1915 everything is now done in a macro.
1916
1917 CT 2k0305
1918 modified to use functions, after Tim Peter's suggestion.
1919
1920 CT 2k0309
1921 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001922
1923 CT 2k0325
1924 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00001925
1926 CT 2k0422
1927 complete rewrite. We now build a chain via ob_type
1928 and save the limited number of types in ob_refcnt.
1929 This is perfect since we don't need any memory.
1930 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00001931*/
1932
Guido van Rossume92e6102000-04-24 15:40:53 +00001933#define Py_TRASHCAN_TUPLE 1
1934#define Py_TRASHCAN_LIST 2
1935#define Py_TRASHCAN_DICT 3
1936#define Py_TRASHCAN_FRAME 4
1937#define Py_TRASHCAN_TRACEBACK 5
1938/* extend here if other objects want protection */
1939
Guido van Rossumd724b232000-03-13 16:01:29 +00001940int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001941
Guido van Rossumd724b232000-03-13 16:01:29 +00001942PyObject * _PyTrash_delete_later = NULL;
1943
1944void
Fred Drake100814d2000-07-09 15:48:49 +00001945_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001946{
Guido van Rossume92e6102000-04-24 15:40:53 +00001947 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001948
Guido van Rossume92e6102000-04-24 15:40:53 +00001949 if (PyTuple_Check(op))
1950 typecode = Py_TRASHCAN_TUPLE;
1951 else if (PyList_Check(op))
1952 typecode = Py_TRASHCAN_LIST;
1953 else if (PyDict_Check(op))
1954 typecode = Py_TRASHCAN_DICT;
1955 else if (PyFrame_Check(op))
1956 typecode = Py_TRASHCAN_FRAME;
1957 else if (PyTraceBack_Check(op))
1958 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00001959 else /* We have a bug here -- those are the only types in GC */ {
1960 Py_FatalError("Type not supported in GC -- internal bug");
1961 return; /* pacify compiler -- execution never here */
1962 }
Guido van Rossume92e6102000-04-24 15:40:53 +00001963 op->ob_refcnt = typecode;
Guido van Rossumd724b232000-03-13 16:01:29 +00001964
Guido van Rossume92e6102000-04-24 15:40:53 +00001965 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
1966 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001967}
1968
1969void
Fred Drake100814d2000-07-09 15:48:49 +00001970_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001971{
1972 while (_PyTrash_delete_later) {
1973 PyObject *shredder = _PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001974 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
1975
1976 switch (shredder->ob_refcnt) {
1977 case Py_TRASHCAN_TUPLE:
1978 shredder->ob_type = &PyTuple_Type;
1979 break;
1980 case Py_TRASHCAN_LIST:
1981 shredder->ob_type = &PyList_Type;
1982 break;
1983 case Py_TRASHCAN_DICT:
1984 shredder->ob_type = &PyDict_Type;
1985 break;
1986 case Py_TRASHCAN_FRAME:
1987 shredder->ob_type = &PyFrame_Type;
1988 break;
1989 case Py_TRASHCAN_TRACEBACK:
1990 shredder->ob_type = &PyTraceBack_Type;
1991 break;
1992 }
1993 _Py_NewReference(shredder);
1994
Guido van Rossumd724b232000-03-13 16:01:29 +00001995 ++_PyTrash_delete_nesting;
1996 Py_DECREF(shredder);
1997 --_PyTrash_delete_nesting;
1998 }
1999}
Neil Schemenauera35c6882001-02-27 04:45:05 +00002000
2001#ifdef WITH_PYMALLOC
2002#include "obmalloc.c"
2003#endif