blob: 88fa34059c82d01ee716a8ddff2c2c308fc6ceaa [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 *
Fred Drake100814d2000-07-09 15:48:49 +0000130_PyObject_NewVar(PyTypeObject *tp, int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000132 PyVarObject *op;
133 op = (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE(tp, size));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000135 return (PyVarObject *)PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000136 return PyObject_INIT_VAR(op, tp, size);
137}
138
139void
Fred Drake100814d2000-07-09 15:48:49 +0000140_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000141{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000142 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143}
144
Guido van Rossum90933611991-06-07 16:10:43 +0000145int
Fred Drake100814d2000-07-09 15:48:49 +0000146PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Guido van Rossum278ef591991-07-27 21:40:24 +0000148 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000150 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000151#ifdef USE_STACKCHECK
152 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000153 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000154 return -1;
155 }
156#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000157 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000158 if (op == NULL) {
159 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160 }
Guido van Rossum90933611991-06-07 16:10:43 +0000161 else {
162 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000163 fprintf(fp, "<refcnt %u at %p>",
164 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000165 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000166 PyObject *s;
167 if (flags & Py_PRINT_RAW)
168 s = PyObject_Str(op);
169 else
170 s = PyObject_Repr(op);
171 if (s == NULL)
172 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000173 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000174 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000175 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000176 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000177 }
Guido van Rossum90933611991-06-07 16:10:43 +0000178 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000179 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000180 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000181 if (ret == 0) {
182 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000184 clearerr(fp);
185 ret = -1;
186 }
187 }
188 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189}
190
Barry Warsaw9bf16442001-01-23 16:24:35 +0000191/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Barry Warsawbbd89b62001-01-24 04:18:13 +0000192void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000193{
Barry Warsaweefb1072001-02-22 22:39:18 +0000194 if (op == NULL)
195 fprintf(stderr, "NULL\n");
196 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000197 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000198 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000199 fprintf(stderr, "\n"
200 "type : %s\n"
201 "refcount: %d\n"
202 "address : %p\n",
203 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
204 op->ob_refcnt,
205 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000206 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000207}
Barry Warsaw903138f2001-01-23 16:33:18 +0000208
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000210PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000213 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000214#ifdef USE_STACKCHECK
215 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000216 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000217 return NULL;
218 }
219#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000220 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000221 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000222 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000223 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000224 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000225 else {
226 PyObject *res;
227 res = (*v->ob_type->tp_repr)(v);
228 if (res == NULL)
229 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000230#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000231 if (PyUnicode_Check(res)) {
232 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000233 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000234 Py_DECREF(res);
235 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000236 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000237 else
238 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000239 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000240#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000241 if (!PyString_Check(res)) {
242 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000243 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000244 res->ob_type->tp_name);
245 Py_DECREF(res);
246 return NULL;
247 }
248 return res;
249 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250}
251
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000252PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000253PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000254{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000255 PyObject *res;
256
Guido van Rossumc6004111993-11-05 10:22:19 +0000257 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000258 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000259 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000260 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000261 return v;
262 }
Tim Peters5a49ade2001-09-11 01:41:59 +0000263 if (PyString_Check(v)) {
264 /* For a string subtype that's not a string, return a true
265 string with the same string data. */
266 PyStringObject *s = (PyStringObject *)v;
267 return PyString_FromStringAndSize(s->ob_sval, s->ob_size);
268 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000269 if (v->ob_type->tp_str == NULL)
270 return PyObject_Repr(v);
271
272 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000273 if (res == NULL)
274 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000275#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000276 if (PyUnicode_Check(res)) {
277 PyObject* str;
278 str = PyUnicode_AsEncodedString(res, NULL, NULL);
279 Py_DECREF(res);
280 if (str)
281 res = str;
282 else
283 return NULL;
284 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000285#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000286 if (!PyString_Check(res)) {
287 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000288 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000289 res->ob_type->tp_name);
290 Py_DECREF(res);
291 return NULL;
292 }
293 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000294}
295
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000296#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000297PyObject *
298PyObject_Unicode(PyObject *v)
299{
300 PyObject *res;
301
302 if (v == NULL)
303 res = PyString_FromString("<NULL>");
304 else if (PyUnicode_Check(v)) {
305 Py_INCREF(v);
306 return v;
307 }
Marc-André Lemburgae605342001-03-25 19:16:13 +0000308 else if (PyString_Check(v)) {
309 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000310 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000311 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000312 else if (v->ob_type->tp_str != NULL)
313 res = (*v->ob_type->tp_str)(v);
314 else {
315 PyObject *func;
316 static PyObject *strstr;
317 if (strstr == NULL) {
318 strstr= PyString_InternFromString("__str__");
319 if (strstr == NULL)
320 return NULL;
321 }
322 if (!PyInstance_Check(v) ||
323 (func = PyObject_GetAttr(v, strstr)) == NULL) {
324 PyErr_Clear();
325 res = PyObject_Repr(v);
326 }
327 else {
328 res = PyEval_CallObject(func, (PyObject *)NULL);
329 Py_DECREF(func);
330 }
331 }
332 if (res == NULL)
333 return NULL;
334 if (!PyUnicode_Check(res)) {
335 PyObject* str;
336 str = PyUnicode_FromObject(res);
337 Py_DECREF(res);
338 if (str)
339 res = str;
340 else
341 return NULL;
342 }
343 return res;
344}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000345#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000346
347
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000348/* Macro to get the tp_richcompare field of a type if defined */
349#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
350 ? (t)->tp_richcompare : NULL)
351
Guido van Rossume797ec12001-01-17 15:24:28 +0000352/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
353static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000354
Guido van Rossume797ec12001-01-17 15:24:28 +0000355/* Try a genuine rich comparison, returning an object. Return:
356 NULL for exception;
357 NotImplemented if this particular rich comparison is not implemented or
358 undefined;
359 some object not equal to NotImplemented if it is implemented
360 (this latter object may not be a Boolean).
361*/
362static PyObject *
363try_rich_compare(PyObject *v, PyObject *w, int op)
364{
365 richcmpfunc f;
366 PyObject *res;
367
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000368 if (v->ob_type != w->ob_type &&
369 PyType_IsSubtype(w->ob_type, v->ob_type) &&
370 (f = RICHCOMPARE(w->ob_type)) != NULL) {
371 res = (*f)(w, v, swapped_op[op]);
372 if (res != Py_NotImplemented)
373 return res;
374 Py_DECREF(res);
375 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000376 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000377 res = (*f)(v, w, 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(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000383 return (*f)(w, v, swapped_op[op]);
384 }
385 res = Py_NotImplemented;
386 Py_INCREF(res);
387 return res;
388}
389
390/* Try a genuine rich comparison, returning an int. Return:
391 -1 for exception (including the case where try_rich_compare() returns an
392 object that's not a Boolean);
393 0 if the outcome is false;
394 1 if the outcome is true;
395 2 if this particular rich comparison is not implemented or undefined.
396*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000397static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000398try_rich_compare_bool(PyObject *v, PyObject *w, int op)
399{
400 PyObject *res;
401 int ok;
402
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000403 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000404 return 2; /* Shortcut, avoid INCREF+DECREF */
405 res = try_rich_compare(v, w, op);
406 if (res == NULL)
407 return -1;
408 if (res == Py_NotImplemented) {
409 Py_DECREF(res);
410 return 2;
411 }
412 ok = PyObject_IsTrue(res);
413 Py_DECREF(res);
414 return ok;
415}
416
417/* Try rich comparisons to determine a 3-way comparison. Return:
418 -2 for an exception;
419 -1 if v < w;
420 0 if v == w;
421 1 if v > w;
422 2 if this particular rich comparison is not implemented or undefined.
423*/
424static int
425try_rich_to_3way_compare(PyObject *v, PyObject *w)
426{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000427 static struct { int op; int outcome; } tries[3] = {
428 /* Try this operator, and if it is true, use this outcome: */
429 {Py_EQ, 0},
430 {Py_LT, -1},
431 {Py_GT, 1},
432 };
433 int i;
434
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000435 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000436 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000437
438 for (i = 0; i < 3; i++) {
439 switch (try_rich_compare_bool(v, w, tries[i].op)) {
440 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000441 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000442 case 1:
443 return tries[i].outcome;
444 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000445 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000446
447 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000448}
449
450/* Try a 3-way comparison, returning an int. Return:
451 -2 for an exception;
452 -1 if v < w;
453 0 if v == w;
454 1 if v > w;
455 2 if this particular 3-way comparison is not implemented or undefined.
456*/
457static int
458try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000459{
460 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000461 cmpfunc f;
462
463 /* Comparisons involving instances are given to instance_compare,
464 which has the same return conventions as this function. */
465
Guido van Rossumab3b0342001-09-18 20:38:53 +0000466 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000467 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000468 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000469 if (PyInstance_Check(w))
470 return (*w->ob_type->tp_compare)(v, w);
471
Guido van Rossumab3b0342001-09-18 20:38:53 +0000472 /* If both have the same (non-NULL) tp_compare, use it. */
473 if (f != NULL && f == w->ob_type->tp_compare) {
474 c = (*f)(v, w);
475 if (c < 0 && PyErr_Occurred())
476 return -1;
477 return c < 0 ? -1 : c > 0 ? 1 : 0;
478 }
479
480 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
481 if (f == _PyObject_SlotCompare ||
482 w->ob_type->tp_compare == _PyObject_SlotCompare)
483 return _PyObject_SlotCompare(v, w);
484
Guido van Rossume797ec12001-01-17 15:24:28 +0000485 /* Try coercion; if it fails, give up */
486 c = PyNumber_CoerceEx(&v, &w);
487 if (c < 0)
488 return -2;
489 if (c > 0)
490 return 2;
491
492 /* Try v's comparison, if defined */
493 if ((f = v->ob_type->tp_compare) != NULL) {
494 c = (*f)(v, w);
495 Py_DECREF(v);
496 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000497 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000498 return -2;
499 return c < 0 ? -1 : c > 0 ? 1 : 0;
500 }
501
502 /* Try w's comparison, if defined */
503 if ((f = w->ob_type->tp_compare) != NULL) {
504 c = (*f)(w, v); /* swapped! */
505 Py_DECREF(v);
506 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000507 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000508 return -2;
509 return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
510 }
511
512 /* No comparison defined */
513 Py_DECREF(v);
514 Py_DECREF(w);
515 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000516}
517
Guido van Rossume797ec12001-01-17 15:24:28 +0000518/* Final fallback 3-way comparison, returning an int. Return:
519 -2 if an error occurred;
520 -1 if v < w;
521 0 if v == w;
522 1 if v > w.
523*/
524static int
525default_3way_compare(PyObject *v, PyObject *w)
526{
527 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000528 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000529
530 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000531 /* When comparing these pointers, they must be cast to
532 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
533 * uintptr_t). ANSI specifies that pointer compares other
534 * than == and != to non-related structures are undefined.
535 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000536 Py_uintptr_t vv = (Py_uintptr_t)v;
537 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000538 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
539 }
540
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000541#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000542 /* Special case for Unicode */
543 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
544 c = PyUnicode_Compare(v, w);
545 if (!PyErr_Occurred())
546 return c;
547 /* TypeErrors are ignored: if Unicode coercion fails due
548 to one of the arguments not having the right type, we
549 continue as defined by the coercion protocol (see
550 above). Luckily, decoding errors are reported as
551 ValueErrors and are not masked by this technique. */
552 if (!PyErr_ExceptionMatches(PyExc_TypeError))
553 return -2;
554 PyErr_Clear();
555 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000556#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000557
Guido van Rossum0871e932001-01-22 19:28:09 +0000558 /* None is smaller than anything */
559 if (v == Py_None)
560 return -1;
561 if (w == Py_None)
562 return 1;
563
Guido van Rossume797ec12001-01-17 15:24:28 +0000564 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000565 if (v->ob_type->tp_as_number)
566 vname = "";
567 else
568 vname = v->ob_type->tp_name;
569 if (w->ob_type->tp_as_number)
570 wname = "";
571 else
572 wname = w->ob_type->tp_name;
573 c = strcmp(vname, wname);
574 if (c < 0)
575 return -1;
576 if (c > 0)
577 return 1;
578 /* Same type name, or (more likely) incomparable numeric types */
579 return ((Py_uintptr_t)(v->ob_type) < (
580 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000581}
582
583#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
584
Tim Peters6d60b2e2001-05-07 20:53:51 +0000585/* Do a 3-way comparison, by hook or by crook. Return:
586 -2 for an exception;
587 -1 if v < w;
588 0 if v == w;
589 1 if v > w;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000590 If the object implements a tp_compare function, it returns
591 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000592*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000593static int
Fred Drake100814d2000-07-09 15:48:49 +0000594do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000595{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000596 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000597 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000598
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000599 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000600 && (f = v->ob_type->tp_compare) != NULL) {
601 c = (*f)(v, w);
602 if (c != 2 || !PyInstance_Check(v))
603 return c;
604 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000605 c = try_rich_to_3way_compare(v, w);
606 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000607 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000608 c = try_3way_compare(v, w);
609 if (c < 2)
610 return c;
611 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000612}
613
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000614/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000615 some types) and decremented on exit. If the count exceeds the
616 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000617
618 This is a tunable parameter that should only affect the performance
619 of comparisons, nothing else. Setting it high makes comparing deeply
620 nested non-cyclical data structures faster, but makes comparing cyclical
621 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000622*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000623#define NESTING_LIMIT 20
624
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000625static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000626
627static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000628get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000629{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000630 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000631 PyObject *tstate_dict, *inprogress;
632
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000633 if (key == NULL) {
634 key = PyString_InternFromString("cmp_state");
635 if (key == NULL)
636 return NULL;
637 }
638
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000639 tstate_dict = PyThreadState_GetDict();
640 if (tstate_dict == NULL) {
641 PyErr_BadInternalCall();
642 return NULL;
643 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000644
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000645 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000646 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000647 inprogress = PyDict_New();
648 if (inprogress == NULL)
649 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000650 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000651 Py_DECREF(inprogress);
652 return NULL;
653 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000654 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000655 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000656
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000657 return inprogress;
658}
659
660static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000661check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000662{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000663 PyObject *inprogress;
664 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000665 Py_uintptr_t iv = (Py_uintptr_t)v;
666 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000667 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000668
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000669 inprogress = get_inprogress_dict();
670 if (inprogress == NULL)
671 return NULL;
672
673 token = PyTuple_New(3);
674 if (token == NULL)
675 return NULL;
676
677 if (iv <= iw) {
678 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
679 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
680 if (op >= 0)
681 op = swapped_op[op];
682 } else {
683 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
684 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
685 }
686 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
687 if (x == NULL || y == NULL || z == NULL) {
688 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000689 return NULL;
690 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000691
692 if (PyDict_GetItem(inprogress, token) != NULL) {
693 Py_DECREF(token);
694 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000695 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000696
697 if (PyDict_SetItem(inprogress, token, token) < 0) {
698 Py_DECREF(token);
699 return NULL;
700 }
701
702 return token;
703}
704
705static void
706delete_token(PyObject *token)
707{
708 PyObject *inprogress;
709
710 if (token == NULL || token == Py_None)
711 return;
712 inprogress = get_inprogress_dict();
713 if (inprogress == NULL)
714 PyErr_Clear();
715 else
716 PyDict_DelItem(inprogress, token);
717 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000718}
719
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000720int
Fred Drake100814d2000-07-09 15:48:49 +0000721PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000723 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000724 int result;
725
Jack Jansend49cbe12000-08-22 21:52:51 +0000726#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000727 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000728 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
729 return -1;
730 }
731#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000732 if (v == NULL || w == NULL) {
733 PyErr_BadInternalCall();
734 return -1;
735 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736 if (v == w)
737 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000738 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000739 compare_nesting++;
740 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000741 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000742 || (vtp->tp_as_sequence
743 && !PyString_Check(v)
744 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000745 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000746 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000747
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000748 if (token == NULL) {
749 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000750 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000751 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000752 /* already comparing these objects. assume
753 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000754 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000755 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000756 else {
757 result = do_cmp(v, w);
758 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000759 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000760 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000761 else {
762 result = do_cmp(v, w);
763 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000764 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000765 return result < 0 ? -1 : result;
766}
767
768static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000769convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000770{
Guido van Rossume797ec12001-01-17 15:24:28 +0000771 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000772 switch (op) {
773 case Py_LT: c = c < 0; break;
774 case Py_LE: c = c <= 0; break;
775 case Py_EQ: c = c == 0; break;
776 case Py_NE: c = c != 0; break;
777 case Py_GT: c = c > 0; break;
778 case Py_GE: c = c >= 0; break;
779 }
780 result = c ? Py_True : Py_False;
781 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000782 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000784
785
786static PyObject *
787try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
788{
789 int c;
790
791 c = try_3way_compare(v, w);
792 if (c >= 2)
793 c = default_3way_compare(v, w);
794 if (c <= -2)
795 return NULL;
796 return convert_3way_to_object(op, c);
797}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000799static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000800do_richcmp(PyObject *v, PyObject *w, int op)
801{
802 PyObject *res;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000803 cmpfunc f;
804
805 /* If the types are equal, don't bother with coercions etc.
806 Instances are special-cased in try_3way_compare, since
807 a result of 2 does *not* mean one value being greater
808 than the other. */
809 if (v->ob_type == w->ob_type
810 && (f = v->ob_type->tp_compare) != NULL
811 && !PyInstance_Check(v)) {
812 int c;
813 richcmpfunc f1;
814 if ((f1 = RICHCOMPARE(v->ob_type)) != NULL) {
815 /* If the type has richcmp, try it first.
816 try_rich_compare would try it two-sided,
817 which is not needed since we've a single
818 type only. */
819 res = (*f1)(v, w, op);
820 if (res != Py_NotImplemented)
821 return res;
822 Py_DECREF(res);
823 }
824 c = (*f)(v, w);
825 if (c < 0 && PyErr_Occurred())
826 return NULL;
827 return convert_3way_to_object(op, c);
828 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000829
830 res = try_rich_compare(v, w, op);
831 if (res != Py_NotImplemented)
832 return res;
833 Py_DECREF(res);
834
835 return try_3way_to_rich_compare(v, w, op);
836}
837
838PyObject *
839PyObject_RichCompare(PyObject *v, PyObject *w, int op)
840{
841 PyObject *res;
842
843 assert(Py_LT <= op && op <= Py_GE);
844
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000845 compare_nesting++;
846 if (compare_nesting > NESTING_LIMIT &&
847 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000848 || (v->ob_type->tp_as_sequence
849 && !PyString_Check(v)
850 && !PyTuple_Check(v)))) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000851 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000852 PyObject *token = check_recursion(v, w, op);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000853
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000854 if (token == NULL) {
855 res = NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000856 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000857 else if (token == Py_None) {
858 /* already comparing these objects with this operator.
859 assume they're equal until shown otherwise */
860 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000861 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000862 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000863 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000864 else {
865 PyErr_SetString(PyExc_ValueError,
866 "can't order recursive values");
867 res = NULL;
868 }
869 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000870 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000871 else {
872 res = do_richcmp(v, w, op);
873 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000874 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000875 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000876 else {
877 res = do_richcmp(v, w, op);
878 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000879 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000880 return res;
881}
882
Tim Petersde9725f2001-05-05 10:06:17 +0000883/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000884int
885PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
886{
887 PyObject *res = PyObject_RichCompare(v, w, op);
888 int ok;
889
890 if (res == NULL)
891 return -1;
892 ok = PyObject_IsTrue(res);
893 Py_DECREF(res);
894 return ok;
895}
Fred Drake13634cf2000-06-29 19:17:04 +0000896
897/* Set of hash utility functions to help maintaining the invariant that
898 iff a==b then hash(a)==hash(b)
899
900 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
901*/
902
903long
Fred Drake100814d2000-07-09 15:48:49 +0000904_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000905{
Tim Peters39dce292000-08-15 03:34:48 +0000906 double intpart, fractpart;
907 int expo;
908 long hipart;
909 long x; /* the final hash value */
910 /* This is designed so that Python numbers of different types
911 * that compare equal hash to the same value; otherwise comparisons
912 * of mapping keys will turn out weird.
913 */
914
915#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
916{
917 extended e;
918 fractpart = modf(v, &e);
919 intpart = e;
920}
921#else
922 fractpart = modf(v, &intpart);
923#endif
924 if (fractpart == 0.0) {
925 /* This must return the same hash as an equal int or long. */
926 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
927 /* Convert to long and use its hash. */
928 PyObject *plong; /* converted to Python long */
929 if (Py_IS_INFINITY(intpart))
930 /* can't convert to long int -- arbitrary */
931 v = v < 0 ? -271828.0 : 314159.0;
932 plong = PyLong_FromDouble(v);
933 if (plong == NULL)
934 return -1;
935 x = PyObject_Hash(plong);
936 Py_DECREF(plong);
937 return x;
938 }
939 /* Fits in a C long == a Python int, so is its own hash. */
940 x = (long)intpart;
941 if (x == -1)
942 x = -2;
943 return x;
944 }
945 /* The fractional part is non-zero, so we don't have to worry about
946 * making this match the hash of some other type.
947 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000948 * Since the VAX D double format has 56 mantissa bits, which is the
949 * most of any double format in use, each of these parts may have as
950 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000951 * So, assuming sizeof(long) >= 4, each part can be broken into two
952 * longs; frexp and multiplication are used to do that.
953 * Also, since the Cray double format has 15 exponent bits, which is
954 * the most of any double format in use, shifting the exponent field
955 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000956 */
Tim Peters39dce292000-08-15 03:34:48 +0000957 v = frexp(v, &expo);
958 v *= 2147483648.0; /* 2**31 */
959 hipart = (long)v; /* take the top 32 bits */
960 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
961 x = hipart + (long)v + (expo << 15);
962 if (x == -1)
963 x = -2;
964 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000965}
966
967long
Fred Drake100814d2000-07-09 15:48:49 +0000968_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000969{
970#if SIZEOF_LONG >= SIZEOF_VOID_P
971 return (long)p;
972#else
973 /* convert to a Python long and hash that */
974 PyObject* longobj;
975 long x;
976
977 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
978 x = -1;
979 goto finally;
980 }
981 x = PyObject_Hash(longobj);
982
983finally:
984 Py_XDECREF(longobj);
985 return x;
986#endif
987}
988
989
Guido van Rossum9bfef441993-03-29 10:43:31 +0000990long
Fred Drake100814d2000-07-09 15:48:49 +0000991PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000992{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000993 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000994 if (tp->tp_hash != NULL)
995 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000996 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000997 return _Py_HashPointer(v); /* Use address as hash value */
998 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000999 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001000 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001001 return -1;
1002}
1003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001004PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001005PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001006{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001008
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001010 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011 w = PyString_InternFromString(name);
1012 if (w == NULL)
1013 return NULL;
1014 res = PyObject_GetAttr(v, w);
1015 Py_XDECREF(w);
1016 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001017}
1018
1019int
Fred Drake100814d2000-07-09 15:48:49 +00001020PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001021{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001022 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001023 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001025 return 1;
1026 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001027 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001028 return 0;
1029}
1030
1031int
Fred Drake100814d2000-07-09 15:48:49 +00001032PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001033{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001034 PyObject *s;
1035 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001036
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001038 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 s = PyString_InternFromString(name);
1040 if (s == NULL)
1041 return -1;
1042 res = PyObject_SetAttr(v, s, w);
1043 Py_XDECREF(s);
1044 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001045}
1046
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001047PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001048PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001049{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050 PyTypeObject *tp = v->ob_type;
1051
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001052#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001053 /* The Unicode to string conversion is done here because the
1054 existing tp_getattro slots expect a string object as name
1055 and we wouldn't want to break those. */
1056 if (PyUnicode_Check(name)) {
1057 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1058 if (name == NULL)
1059 return NULL;
1060 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001061#endif
1062
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001063 if (!PyString_Check(name)) {
1064 PyErr_SetString(PyExc_TypeError,
1065 "attribute name must be string");
1066 return NULL;
1067 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001068 if (tp->tp_getattro != NULL)
1069 return (*tp->tp_getattro)(v, name);
1070 if (tp->tp_getattr != NULL)
1071 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1072 PyErr_Format(PyExc_AttributeError,
1073 "'%.50s' object has no attribute '%.400s'",
1074 tp->tp_name, PyString_AS_STRING(name));
1075 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001076}
1077
1078int
Fred Drake100814d2000-07-09 15:48:49 +00001079PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001080{
1081 PyObject *res = PyObject_GetAttr(v, name);
1082 if (res != NULL) {
1083 Py_DECREF(res);
1084 return 1;
1085 }
1086 PyErr_Clear();
1087 return 0;
1088}
1089
1090int
Fred Drake100814d2000-07-09 15:48:49 +00001091PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001092{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001094 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001095
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001096#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001097 /* The Unicode to string conversion is done here because the
1098 existing tp_setattro slots expect a string object as name
1099 and we wouldn't want to break those. */
1100 if (PyUnicode_Check(name)) {
1101 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1102 if (name == NULL)
1103 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001104 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001105 else
1106#endif
1107 if (!PyString_Check(name)){
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001108 PyErr_SetString(PyExc_TypeError,
1109 "attribute name must be string");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001110 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 else
1113 Py_INCREF(name);
1114
1115 PyString_InternInPlace(&name);
1116 if (tp->tp_setattro != NULL) {
1117 err = (*tp->tp_setattro)(v, name, value);
1118 Py_DECREF(name);
1119 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001120 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 if (tp->tp_setattr != NULL) {
1122 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1123 Py_DECREF(name);
1124 return err;
1125 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001126 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1128 PyErr_Format(PyExc_TypeError,
1129 "'%.100s' object has no attributes "
1130 "(%s .%.100s)",
1131 tp->tp_name,
1132 value==NULL ? "del" : "assign to",
1133 PyString_AS_STRING(name));
1134 else
1135 PyErr_Format(PyExc_TypeError,
1136 "'%.100s' object has only read-only attributes "
1137 "(%s .%.100s)",
1138 tp->tp_name,
1139 value==NULL ? "del" : "assign to",
1140 PyString_AS_STRING(name));
1141 return -1;
1142}
1143
1144/* Helper to get a pointer to an object's __dict__ slot, if any */
1145
1146PyObject **
1147_PyObject_GetDictPtr(PyObject *obj)
1148{
1149#define PTRSIZE (sizeof(PyObject *))
1150
1151 long dictoffset;
1152 PyTypeObject *tp = obj->ob_type;
1153
1154 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1155 return NULL;
1156 dictoffset = tp->tp_dictoffset;
1157 if (dictoffset == 0)
1158 return NULL;
1159 if (dictoffset < 0) {
Neil Schemenauerfd343692001-08-29 23:54:03 +00001160 dictoffset += tp->tp_basicsize;
Guido van Rossumdd4d1c42001-09-20 13:38:22 +00001161 dictoffset += tp->tp_itemsize * ((PyVarObject *)obj)->ob_size;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162 assert(dictoffset > 0); /* Sanity check */
Guido van Rossumdd4d1c42001-09-20 13:38:22 +00001163 /* Round up, if necessary */
1164 if (dictoffset % PTRSIZE != 0) {
1165 dictoffset /= PTRSIZE;
1166 dictoffset += 1;
1167 dictoffset *= PTRSIZE;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001168 }
1169 }
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
Fred Drake41deb1e2001-02-01 05:27:45 +00001844/* Hook to clear up weak references only once the _weakref module is
1845 imported. We use a dummy implementation to simplify the code at each
1846 call site instead of requiring a test for NULL.
1847*/
1848
Fred Drakeb60654b2001-02-26 18:56:37 +00001849static void
Fred Drake41deb1e2001-02-01 05:27:45 +00001850empty_clear_weak_refs(PyObject *o)
1851{
Fred Drakeb60654b2001-02-26 18:56:37 +00001852 return;
Fred Drake41deb1e2001-02-01 05:27:45 +00001853}
1854
Fred Drakeb60654b2001-02-26 18:56:37 +00001855void (*PyObject_ClearWeakRefs)(PyObject *) = empty_clear_weak_refs;
Fred Drake41deb1e2001-02-01 05:27:45 +00001856
1857
1858
Guido van Rossum86610361998-04-10 22:32:46 +00001859/* These methods are used to control infinite recursion in repr, str, print,
1860 etc. Container objects that may recursively contain themselves,
1861 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1862 Py_ReprLeave() to avoid infinite recursion.
1863
1864 Py_ReprEnter() returns 0 the first time it is called for a particular
1865 object and 1 every time thereafter. It returns -1 if an exception
1866 occurred. Py_ReprLeave() has no return value.
1867
1868 See dictobject.c and listobject.c for examples of use.
1869*/
1870
1871#define KEY "Py_Repr"
1872
1873int
Fred Drake100814d2000-07-09 15:48:49 +00001874Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001875{
1876 PyObject *dict;
1877 PyObject *list;
1878 int i;
1879
1880 dict = PyThreadState_GetDict();
1881 if (dict == NULL)
1882 return -1;
1883 list = PyDict_GetItemString(dict, KEY);
1884 if (list == NULL) {
1885 list = PyList_New(0);
1886 if (list == NULL)
1887 return -1;
1888 if (PyDict_SetItemString(dict, KEY, list) < 0)
1889 return -1;
1890 Py_DECREF(list);
1891 }
1892 i = PyList_GET_SIZE(list);
1893 while (--i >= 0) {
1894 if (PyList_GET_ITEM(list, i) == obj)
1895 return 1;
1896 }
1897 PyList_Append(list, obj);
1898 return 0;
1899}
1900
1901void
Fred Drake100814d2000-07-09 15:48:49 +00001902Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001903{
1904 PyObject *dict;
1905 PyObject *list;
1906 int i;
1907
1908 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001909 if (dict == NULL)
1910 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001911 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001912 if (list == NULL || !PyList_Check(list))
1913 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001914 i = PyList_GET_SIZE(list);
1915 /* Count backwards because we always expect obj to be list[-1] */
1916 while (--i >= 0) {
1917 if (PyList_GET_ITEM(list, i) == obj) {
1918 PyList_SetSlice(list, i, i + 1, NULL);
1919 break;
1920 }
1921 }
1922}
Guido van Rossumd724b232000-03-13 16:01:29 +00001923
1924/*
1925 trashcan
1926 CT 2k0130
1927 non-recursively destroy nested objects
1928
1929 CT 2k0223
1930 everything is now done in a macro.
1931
1932 CT 2k0305
1933 modified to use functions, after Tim Peter's suggestion.
1934
1935 CT 2k0309
1936 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001937
1938 CT 2k0325
1939 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00001940
1941 CT 2k0422
1942 complete rewrite. We now build a chain via ob_type
1943 and save the limited number of types in ob_refcnt.
1944 This is perfect since we don't need any memory.
1945 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00001946*/
1947
Guido van Rossume92e6102000-04-24 15:40:53 +00001948#define Py_TRASHCAN_TUPLE 1
1949#define Py_TRASHCAN_LIST 2
1950#define Py_TRASHCAN_DICT 3
1951#define Py_TRASHCAN_FRAME 4
1952#define Py_TRASHCAN_TRACEBACK 5
1953/* extend here if other objects want protection */
1954
Guido van Rossumd724b232000-03-13 16:01:29 +00001955int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001956
Guido van Rossumd724b232000-03-13 16:01:29 +00001957PyObject * _PyTrash_delete_later = NULL;
1958
1959void
Fred Drake100814d2000-07-09 15:48:49 +00001960_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001961{
Guido van Rossume92e6102000-04-24 15:40:53 +00001962 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001963
Guido van Rossume92e6102000-04-24 15:40:53 +00001964 if (PyTuple_Check(op))
1965 typecode = Py_TRASHCAN_TUPLE;
1966 else if (PyList_Check(op))
1967 typecode = Py_TRASHCAN_LIST;
1968 else if (PyDict_Check(op))
1969 typecode = Py_TRASHCAN_DICT;
1970 else if (PyFrame_Check(op))
1971 typecode = Py_TRASHCAN_FRAME;
1972 else if (PyTraceBack_Check(op))
1973 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00001974 else /* We have a bug here -- those are the only types in GC */ {
1975 Py_FatalError("Type not supported in GC -- internal bug");
1976 return; /* pacify compiler -- execution never here */
1977 }
Guido van Rossume92e6102000-04-24 15:40:53 +00001978 op->ob_refcnt = typecode;
Guido van Rossumd724b232000-03-13 16:01:29 +00001979
Guido van Rossume92e6102000-04-24 15:40:53 +00001980 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
1981 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001982}
1983
1984void
Fred Drake100814d2000-07-09 15:48:49 +00001985_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001986{
1987 while (_PyTrash_delete_later) {
1988 PyObject *shredder = _PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001989 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
1990
1991 switch (shredder->ob_refcnt) {
1992 case Py_TRASHCAN_TUPLE:
1993 shredder->ob_type = &PyTuple_Type;
1994 break;
1995 case Py_TRASHCAN_LIST:
1996 shredder->ob_type = &PyList_Type;
1997 break;
1998 case Py_TRASHCAN_DICT:
1999 shredder->ob_type = &PyDict_Type;
2000 break;
2001 case Py_TRASHCAN_FRAME:
2002 shredder->ob_type = &PyFrame_Type;
2003 break;
2004 case Py_TRASHCAN_TRACEBACK:
2005 shredder->ob_type = &PyTraceBack_Type;
2006 break;
2007 }
2008 _Py_NewReference(shredder);
2009
Guido van Rossumd724b232000-03-13 16:01:29 +00002010 ++_PyTrash_delete_nesting;
2011 Py_DECREF(shredder);
2012 --_PyTrash_delete_nesting;
2013 }
2014}
Neil Schemenauera35c6882001-02-27 04:45:05 +00002015
2016#ifdef WITH_PYMALLOC
2017#include "obmalloc.c"
2018#endif