blob: af0c0bbed053aee2f2bd9fc2ff44b1145a2b7e7d [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>");
299 else if (PyUnicode_Check(v)) {
300 Py_INCREF(v);
301 return v;
302 }
Marc-André Lemburgae605342001-03-25 19:16:13 +0000303 else if (PyString_Check(v)) {
304 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000305 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000306 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000307 else if (v->ob_type->tp_str != NULL)
308 res = (*v->ob_type->tp_str)(v);
309 else {
310 PyObject *func;
311 static PyObject *strstr;
312 if (strstr == NULL) {
313 strstr= PyString_InternFromString("__str__");
314 if (strstr == NULL)
315 return NULL;
316 }
317 if (!PyInstance_Check(v) ||
318 (func = PyObject_GetAttr(v, strstr)) == NULL) {
319 PyErr_Clear();
320 res = PyObject_Repr(v);
321 }
322 else {
323 res = PyEval_CallObject(func, (PyObject *)NULL);
324 Py_DECREF(func);
325 }
326 }
327 if (res == NULL)
328 return NULL;
329 if (!PyUnicode_Check(res)) {
330 PyObject* str;
331 str = PyUnicode_FromObject(res);
332 Py_DECREF(res);
333 if (str)
334 res = str;
335 else
336 return NULL;
337 }
338 return res;
339}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000340#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000341
342
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000343/* Macro to get the tp_richcompare field of a type if defined */
344#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
345 ? (t)->tp_richcompare : NULL)
346
Guido van Rossume797ec12001-01-17 15:24:28 +0000347/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
348static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000349
Guido van Rossume797ec12001-01-17 15:24:28 +0000350/* Try a genuine rich comparison, returning an object. Return:
351 NULL for exception;
352 NotImplemented if this particular rich comparison is not implemented or
353 undefined;
354 some object not equal to NotImplemented if it is implemented
355 (this latter object may not be a Boolean).
356*/
357static PyObject *
358try_rich_compare(PyObject *v, PyObject *w, int op)
359{
360 richcmpfunc f;
361 PyObject *res;
362
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000363 if (v->ob_type != w->ob_type &&
364 PyType_IsSubtype(w->ob_type, v->ob_type) &&
365 (f = RICHCOMPARE(w->ob_type)) != NULL) {
366 res = (*f)(w, v, swapped_op[op]);
367 if (res != Py_NotImplemented)
368 return res;
369 Py_DECREF(res);
370 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000371 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000372 res = (*f)(v, w, op);
373 if (res != Py_NotImplemented)
374 return res;
375 Py_DECREF(res);
376 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000377 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000378 return (*f)(w, v, swapped_op[op]);
379 }
380 res = Py_NotImplemented;
381 Py_INCREF(res);
382 return res;
383}
384
385/* Try a genuine rich comparison, returning an int. Return:
386 -1 for exception (including the case where try_rich_compare() returns an
387 object that's not a Boolean);
388 0 if the outcome is false;
389 1 if the outcome is true;
390 2 if this particular rich comparison is not implemented or undefined.
391*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000392static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000393try_rich_compare_bool(PyObject *v, PyObject *w, int op)
394{
395 PyObject *res;
396 int ok;
397
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000398 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000399 return 2; /* Shortcut, avoid INCREF+DECREF */
400 res = try_rich_compare(v, w, op);
401 if (res == NULL)
402 return -1;
403 if (res == Py_NotImplemented) {
404 Py_DECREF(res);
405 return 2;
406 }
407 ok = PyObject_IsTrue(res);
408 Py_DECREF(res);
409 return ok;
410}
411
412/* Try rich comparisons to determine a 3-way comparison. Return:
413 -2 for an exception;
414 -1 if v < w;
415 0 if v == w;
416 1 if v > w;
417 2 if this particular rich comparison is not implemented or undefined.
418*/
419static int
420try_rich_to_3way_compare(PyObject *v, PyObject *w)
421{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000422 static struct { int op; int outcome; } tries[3] = {
423 /* Try this operator, and if it is true, use this outcome: */
424 {Py_EQ, 0},
425 {Py_LT, -1},
426 {Py_GT, 1},
427 };
428 int i;
429
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000430 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000431 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000432
433 for (i = 0; i < 3; i++) {
434 switch (try_rich_compare_bool(v, w, tries[i].op)) {
435 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000436 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000437 case 1:
438 return tries[i].outcome;
439 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000440 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000441
442 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000443}
444
445/* Try a 3-way comparison, returning an int. Return:
446 -2 for an exception;
447 -1 if v < w;
448 0 if v == w;
449 1 if v > w;
450 2 if this particular 3-way comparison is not implemented or undefined.
451*/
452static int
453try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000454{
455 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000456 cmpfunc f;
457
458 /* Comparisons involving instances are given to instance_compare,
459 which has the same return conventions as this function. */
460
Guido van Rossumab3b0342001-09-18 20:38:53 +0000461 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000462 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000463 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000464 if (PyInstance_Check(w))
465 return (*w->ob_type->tp_compare)(v, w);
466
Guido van Rossumab3b0342001-09-18 20:38:53 +0000467 /* If both have the same (non-NULL) tp_compare, use it. */
468 if (f != NULL && f == w->ob_type->tp_compare) {
469 c = (*f)(v, w);
470 if (c < 0 && PyErr_Occurred())
471 return -1;
472 return c < 0 ? -1 : c > 0 ? 1 : 0;
473 }
474
475 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
476 if (f == _PyObject_SlotCompare ||
477 w->ob_type->tp_compare == _PyObject_SlotCompare)
478 return _PyObject_SlotCompare(v, w);
479
Guido van Rossume797ec12001-01-17 15:24:28 +0000480 /* Try coercion; if it fails, give up */
481 c = PyNumber_CoerceEx(&v, &w);
482 if (c < 0)
483 return -2;
484 if (c > 0)
485 return 2;
486
487 /* Try v's comparison, if defined */
488 if ((f = v->ob_type->tp_compare) != NULL) {
489 c = (*f)(v, w);
490 Py_DECREF(v);
491 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000492 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000493 return -2;
494 return c < 0 ? -1 : c > 0 ? 1 : 0;
495 }
496
497 /* Try w's comparison, if defined */
498 if ((f = w->ob_type->tp_compare) != NULL) {
499 c = (*f)(w, v); /* swapped! */
500 Py_DECREF(v);
501 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000502 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000503 return -2;
504 return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
505 }
506
507 /* No comparison defined */
508 Py_DECREF(v);
509 Py_DECREF(w);
510 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000511}
512
Guido van Rossume797ec12001-01-17 15:24:28 +0000513/* Final fallback 3-way comparison, returning an int. Return:
514 -2 if an error occurred;
515 -1 if v < w;
516 0 if v == w;
517 1 if v > w.
518*/
519static int
520default_3way_compare(PyObject *v, PyObject *w)
521{
522 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000523 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000524
525 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000526 /* When comparing these pointers, they must be cast to
527 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
528 * uintptr_t). ANSI specifies that pointer compares other
529 * than == and != to non-related structures are undefined.
530 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000531 Py_uintptr_t vv = (Py_uintptr_t)v;
532 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000533 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
534 }
535
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000536#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000537 /* Special case for Unicode */
538 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
539 c = PyUnicode_Compare(v, w);
540 if (!PyErr_Occurred())
541 return c;
542 /* TypeErrors are ignored: if Unicode coercion fails due
543 to one of the arguments not having the right type, we
544 continue as defined by the coercion protocol (see
545 above). Luckily, decoding errors are reported as
546 ValueErrors and are not masked by this technique. */
547 if (!PyErr_ExceptionMatches(PyExc_TypeError))
548 return -2;
549 PyErr_Clear();
550 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000551#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000552
Guido van Rossum0871e932001-01-22 19:28:09 +0000553 /* None is smaller than anything */
554 if (v == Py_None)
555 return -1;
556 if (w == Py_None)
557 return 1;
558
Guido van Rossume797ec12001-01-17 15:24:28 +0000559 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000560 if (v->ob_type->tp_as_number)
561 vname = "";
562 else
563 vname = v->ob_type->tp_name;
564 if (w->ob_type->tp_as_number)
565 wname = "";
566 else
567 wname = w->ob_type->tp_name;
568 c = strcmp(vname, wname);
569 if (c < 0)
570 return -1;
571 if (c > 0)
572 return 1;
573 /* Same type name, or (more likely) incomparable numeric types */
574 return ((Py_uintptr_t)(v->ob_type) < (
575 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000576}
577
578#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
579
Tim Peters6d60b2e2001-05-07 20:53:51 +0000580/* Do a 3-way comparison, by hook or by crook. Return:
581 -2 for an exception;
582 -1 if v < w;
583 0 if v == w;
584 1 if v > w;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000585 If the object implements a tp_compare function, it returns
586 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000587*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000588static int
Fred Drake100814d2000-07-09 15:48:49 +0000589do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000590{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000591 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000592 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000593
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000594 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000595 && (f = v->ob_type->tp_compare) != NULL) {
596 c = (*f)(v, w);
597 if (c != 2 || !PyInstance_Check(v))
598 return c;
599 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000600 c = try_rich_to_3way_compare(v, w);
601 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000602 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000603 c = try_3way_compare(v, w);
604 if (c < 2)
605 return c;
606 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000607}
608
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000609/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000610 some types) and decremented on exit. If the count exceeds the
611 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000612
613 This is a tunable parameter that should only affect the performance
614 of comparisons, nothing else. Setting it high makes comparing deeply
615 nested non-cyclical data structures faster, but makes comparing cyclical
616 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000617*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000618#define NESTING_LIMIT 20
619
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000620static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000621
622static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000623get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000624{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000625 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000626 PyObject *tstate_dict, *inprogress;
627
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000628 if (key == NULL) {
629 key = PyString_InternFromString("cmp_state");
630 if (key == NULL)
631 return NULL;
632 }
633
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000634 tstate_dict = PyThreadState_GetDict();
635 if (tstate_dict == NULL) {
636 PyErr_BadInternalCall();
637 return NULL;
638 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000639
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000640 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000641 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000642 inprogress = PyDict_New();
643 if (inprogress == NULL)
644 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000645 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000646 Py_DECREF(inprogress);
647 return NULL;
648 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000649 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000650 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000651
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000652 return inprogress;
653}
654
655static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000656check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000657{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000658 PyObject *inprogress;
659 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000660 Py_uintptr_t iv = (Py_uintptr_t)v;
661 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000662 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000663
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000664 inprogress = get_inprogress_dict();
665 if (inprogress == NULL)
666 return NULL;
667
668 token = PyTuple_New(3);
669 if (token == NULL)
670 return NULL;
671
672 if (iv <= iw) {
673 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
674 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
675 if (op >= 0)
676 op = swapped_op[op];
677 } else {
678 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
679 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
680 }
681 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
682 if (x == NULL || y == NULL || z == NULL) {
683 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000684 return NULL;
685 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000686
687 if (PyDict_GetItem(inprogress, token) != NULL) {
688 Py_DECREF(token);
689 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000690 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000691
692 if (PyDict_SetItem(inprogress, token, token) < 0) {
693 Py_DECREF(token);
694 return NULL;
695 }
696
697 return token;
698}
699
700static void
701delete_token(PyObject *token)
702{
703 PyObject *inprogress;
704
705 if (token == NULL || token == Py_None)
706 return;
707 inprogress = get_inprogress_dict();
708 if (inprogress == NULL)
709 PyErr_Clear();
710 else
711 PyDict_DelItem(inprogress, token);
712 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000713}
714
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715int
Fred Drake100814d2000-07-09 15:48:49 +0000716PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000717{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000718 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000719 int result;
720
Jack Jansend49cbe12000-08-22 21:52:51 +0000721#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000722 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000723 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
724 return -1;
725 }
726#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000727 if (v == NULL || w == NULL) {
728 PyErr_BadInternalCall();
729 return -1;
730 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731 if (v == w)
732 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000733 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000734 compare_nesting++;
735 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000736 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000737 || (vtp->tp_as_sequence
738 && !PyString_Check(v)
739 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000740 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000741 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000742
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000743 if (token == NULL) {
744 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000745 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000746 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000747 /* already comparing these objects. assume
748 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000749 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000750 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000751 else {
752 result = do_cmp(v, w);
753 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000754 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000755 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000756 else {
757 result = do_cmp(v, w);
758 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000759 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000760 return result < 0 ? -1 : result;
761}
762
763static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000764convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000765{
Guido van Rossume797ec12001-01-17 15:24:28 +0000766 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000767 switch (op) {
768 case Py_LT: c = c < 0; break;
769 case Py_LE: c = c <= 0; break;
770 case Py_EQ: c = c == 0; break;
771 case Py_NE: c = c != 0; break;
772 case Py_GT: c = c > 0; break;
773 case Py_GE: c = c >= 0; break;
774 }
775 result = c ? Py_True : Py_False;
776 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000777 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000779
780
781static PyObject *
782try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
783{
784 int c;
785
786 c = try_3way_compare(v, w);
787 if (c >= 2)
788 c = default_3way_compare(v, w);
789 if (c <= -2)
790 return NULL;
791 return convert_3way_to_object(op, c);
792}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000793
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000794static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000795do_richcmp(PyObject *v, PyObject *w, int op)
796{
797 PyObject *res;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000798 cmpfunc f;
799
800 /* If the types are equal, don't bother with coercions etc.
801 Instances are special-cased in try_3way_compare, since
802 a result of 2 does *not* mean one value being greater
803 than the other. */
804 if (v->ob_type == w->ob_type
805 && (f = v->ob_type->tp_compare) != NULL
806 && !PyInstance_Check(v)) {
807 int c;
808 richcmpfunc f1;
809 if ((f1 = RICHCOMPARE(v->ob_type)) != NULL) {
810 /* If the type has richcmp, try it first.
811 try_rich_compare would try it two-sided,
812 which is not needed since we've a single
813 type only. */
814 res = (*f1)(v, w, op);
815 if (res != Py_NotImplemented)
816 return res;
817 Py_DECREF(res);
818 }
819 c = (*f)(v, w);
820 if (c < 0 && PyErr_Occurred())
821 return NULL;
822 return convert_3way_to_object(op, c);
823 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000824
825 res = try_rich_compare(v, w, op);
826 if (res != Py_NotImplemented)
827 return res;
828 Py_DECREF(res);
829
830 return try_3way_to_rich_compare(v, w, op);
831}
832
833PyObject *
834PyObject_RichCompare(PyObject *v, PyObject *w, int op)
835{
836 PyObject *res;
837
838 assert(Py_LT <= op && op <= Py_GE);
839
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000840 compare_nesting++;
841 if (compare_nesting > NESTING_LIMIT &&
842 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000843 || (v->ob_type->tp_as_sequence
844 && !PyString_Check(v)
845 && !PyTuple_Check(v)))) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000846 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000847 PyObject *token = check_recursion(v, w, op);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000848
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000849 if (token == NULL) {
850 res = NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000851 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000852 else if (token == Py_None) {
853 /* already comparing these objects with this operator.
854 assume they're equal until shown otherwise */
855 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000856 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000857 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000858 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000859 else {
860 PyErr_SetString(PyExc_ValueError,
861 "can't order recursive values");
862 res = NULL;
863 }
864 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000865 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000866 else {
867 res = do_richcmp(v, w, op);
868 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000869 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000870 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000871 else {
872 res = do_richcmp(v, w, op);
873 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000874 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000875 return res;
876}
877
Tim Petersde9725f2001-05-05 10:06:17 +0000878/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000879int
880PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
881{
882 PyObject *res = PyObject_RichCompare(v, w, op);
883 int ok;
884
885 if (res == NULL)
886 return -1;
887 ok = PyObject_IsTrue(res);
888 Py_DECREF(res);
889 return ok;
890}
Fred Drake13634cf2000-06-29 19:17:04 +0000891
892/* Set of hash utility functions to help maintaining the invariant that
893 iff a==b then hash(a)==hash(b)
894
895 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
896*/
897
898long
Fred Drake100814d2000-07-09 15:48:49 +0000899_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000900{
Tim Peters39dce292000-08-15 03:34:48 +0000901 double intpart, fractpart;
902 int expo;
903 long hipart;
904 long x; /* the final hash value */
905 /* This is designed so that Python numbers of different types
906 * that compare equal hash to the same value; otherwise comparisons
907 * of mapping keys will turn out weird.
908 */
909
910#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
911{
912 extended e;
913 fractpart = modf(v, &e);
914 intpart = e;
915}
916#else
917 fractpart = modf(v, &intpart);
918#endif
919 if (fractpart == 0.0) {
920 /* This must return the same hash as an equal int or long. */
921 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
922 /* Convert to long and use its hash. */
923 PyObject *plong; /* converted to Python long */
924 if (Py_IS_INFINITY(intpart))
925 /* can't convert to long int -- arbitrary */
926 v = v < 0 ? -271828.0 : 314159.0;
927 plong = PyLong_FromDouble(v);
928 if (plong == NULL)
929 return -1;
930 x = PyObject_Hash(plong);
931 Py_DECREF(plong);
932 return x;
933 }
934 /* Fits in a C long == a Python int, so is its own hash. */
935 x = (long)intpart;
936 if (x == -1)
937 x = -2;
938 return x;
939 }
940 /* The fractional part is non-zero, so we don't have to worry about
941 * making this match the hash of some other type.
942 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000943 * Since the VAX D double format has 56 mantissa bits, which is the
944 * most of any double format in use, each of these parts may have as
945 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000946 * So, assuming sizeof(long) >= 4, each part can be broken into two
947 * longs; frexp and multiplication are used to do that.
948 * Also, since the Cray double format has 15 exponent bits, which is
949 * the most of any double format in use, shifting the exponent field
950 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000951 */
Tim Peters39dce292000-08-15 03:34:48 +0000952 v = frexp(v, &expo);
953 v *= 2147483648.0; /* 2**31 */
954 hipart = (long)v; /* take the top 32 bits */
955 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
956 x = hipart + (long)v + (expo << 15);
957 if (x == -1)
958 x = -2;
959 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000960}
961
962long
Fred Drake100814d2000-07-09 15:48:49 +0000963_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000964{
965#if SIZEOF_LONG >= SIZEOF_VOID_P
966 return (long)p;
967#else
968 /* convert to a Python long and hash that */
969 PyObject* longobj;
970 long x;
971
972 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
973 x = -1;
974 goto finally;
975 }
976 x = PyObject_Hash(longobj);
977
978finally:
979 Py_XDECREF(longobj);
980 return x;
981#endif
982}
983
984
Guido van Rossum9bfef441993-03-29 10:43:31 +0000985long
Fred Drake100814d2000-07-09 15:48:49 +0000986PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000987{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000988 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000989 if (tp->tp_hash != NULL)
990 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000991 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000992 return _Py_HashPointer(v); /* Use address as hash value */
993 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000994 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000995 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000996 return -1;
997}
998
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000999PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001000PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001001{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001003
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001005 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 w = PyString_InternFromString(name);
1007 if (w == NULL)
1008 return NULL;
1009 res = PyObject_GetAttr(v, w);
1010 Py_XDECREF(w);
1011 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001012}
1013
1014int
Fred Drake100814d2000-07-09 15:48:49 +00001015PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001016{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001017 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001018 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001020 return 1;
1021 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001022 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001023 return 0;
1024}
1025
1026int
Fred Drake100814d2000-07-09 15:48:49 +00001027PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001028{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 PyObject *s;
1030 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001031
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001033 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001034 s = PyString_InternFromString(name);
1035 if (s == NULL)
1036 return -1;
1037 res = PyObject_SetAttr(v, s, w);
1038 Py_XDECREF(s);
1039 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001040}
1041
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001042PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001043PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001044{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045 PyTypeObject *tp = v->ob_type;
1046
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001047#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001048 /* The Unicode to string conversion is done here because the
1049 existing tp_getattro slots expect a string object as name
1050 and we wouldn't want to break those. */
1051 if (PyUnicode_Check(name)) {
1052 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1053 if (name == NULL)
1054 return NULL;
1055 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001056#endif
1057
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001058 if (!PyString_Check(name)) {
1059 PyErr_SetString(PyExc_TypeError,
1060 "attribute name must be string");
1061 return NULL;
1062 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 if (tp->tp_getattro != NULL)
1064 return (*tp->tp_getattro)(v, name);
1065 if (tp->tp_getattr != NULL)
1066 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1067 PyErr_Format(PyExc_AttributeError,
1068 "'%.50s' object has no attribute '%.400s'",
1069 tp->tp_name, PyString_AS_STRING(name));
1070 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001071}
1072
1073int
Fred Drake100814d2000-07-09 15:48:49 +00001074PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001075{
1076 PyObject *res = PyObject_GetAttr(v, name);
1077 if (res != NULL) {
1078 Py_DECREF(res);
1079 return 1;
1080 }
1081 PyErr_Clear();
1082 return 0;
1083}
1084
1085int
Fred Drake100814d2000-07-09 15:48:49 +00001086PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001087{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001089 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001090
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001091#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001092 /* The Unicode to string conversion is done here because the
1093 existing tp_setattro slots expect a string object as name
1094 and we wouldn't want to break those. */
1095 if (PyUnicode_Check(name)) {
1096 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1097 if (name == NULL)
1098 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001099 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001100 else
1101#endif
1102 if (!PyString_Check(name)){
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001103 PyErr_SetString(PyExc_TypeError,
1104 "attribute name must be string");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001105 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001106 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 else
1108 Py_INCREF(name);
1109
1110 PyString_InternInPlace(&name);
1111 if (tp->tp_setattro != NULL) {
1112 err = (*tp->tp_setattro)(v, name, value);
1113 Py_DECREF(name);
1114 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001115 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 if (tp->tp_setattr != NULL) {
1117 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1118 Py_DECREF(name);
1119 return err;
1120 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001121 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1123 PyErr_Format(PyExc_TypeError,
1124 "'%.100s' object has no attributes "
1125 "(%s .%.100s)",
1126 tp->tp_name,
1127 value==NULL ? "del" : "assign to",
1128 PyString_AS_STRING(name));
1129 else
1130 PyErr_Format(PyExc_TypeError,
1131 "'%.100s' object has only read-only attributes "
1132 "(%s .%.100s)",
1133 tp->tp_name,
1134 value==NULL ? "del" : "assign to",
1135 PyString_AS_STRING(name));
1136 return -1;
1137}
1138
1139/* Helper to get a pointer to an object's __dict__ slot, if any */
1140
1141PyObject **
1142_PyObject_GetDictPtr(PyObject *obj)
1143{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144 long dictoffset;
1145 PyTypeObject *tp = obj->ob_type;
1146
1147 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1148 return NULL;
1149 dictoffset = tp->tp_dictoffset;
1150 if (dictoffset == 0)
1151 return NULL;
1152 if (dictoffset < 0) {
Tim Petersf2a67da2001-10-07 03:54:51 +00001153 const size_t size = _PyObject_VAR_SIZE(tp,
1154 ((PyVarObject *)obj)->ob_size);
Tim Peters6d483d32001-10-06 21:27:34 +00001155 dictoffset += (long)size;
1156 assert(dictoffset > 0);
1157 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001158 }
1159 return (PyObject **) ((char *)obj + dictoffset);
1160}
1161
1162/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1163
1164PyObject *
1165PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1166{
1167 PyTypeObject *tp = obj->ob_type;
1168 PyObject *descr;
1169 descrgetfunc f;
1170 PyObject **dictptr;
1171
1172 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001173 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174 return NULL;
1175 }
1176
1177 descr = _PyType_Lookup(tp, name);
1178 f = NULL;
1179 if (descr != NULL) {
1180 f = descr->ob_type->tp_descr_get;
1181 if (f != NULL && PyDescr_IsData(descr))
1182 return f(descr, obj, (PyObject *)obj->ob_type);
1183 }
1184
1185 dictptr = _PyObject_GetDictPtr(obj);
1186 if (dictptr != NULL) {
1187 PyObject *dict = *dictptr;
1188 if (dict != NULL) {
1189 PyObject *res = PyDict_GetItem(dict, name);
1190 if (res != NULL) {
1191 Py_INCREF(res);
1192 return res;
1193 }
1194 }
1195 }
1196
1197 if (f != NULL)
1198 return f(descr, obj, (PyObject *)obj->ob_type);
1199
1200 if (descr != NULL) {
1201 Py_INCREF(descr);
1202 return descr;
1203 }
1204
1205 PyErr_Format(PyExc_AttributeError,
1206 "'%.50s' object has no attribute '%.400s'",
1207 tp->tp_name, PyString_AS_STRING(name));
1208 return NULL;
1209}
1210
1211int
1212PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1213{
1214 PyTypeObject *tp = obj->ob_type;
1215 PyObject *descr;
1216 descrsetfunc f;
1217 PyObject **dictptr;
1218
1219 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001220 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 return -1;
1222 }
1223
1224 descr = _PyType_Lookup(tp, name);
1225 f = NULL;
1226 if (descr != NULL) {
1227 f = descr->ob_type->tp_descr_set;
1228 if (f != NULL && PyDescr_IsData(descr))
1229 return f(descr, obj, value);
1230 }
1231
1232 dictptr = _PyObject_GetDictPtr(obj);
1233 if (dictptr != NULL) {
1234 PyObject *dict = *dictptr;
1235 if (dict == NULL && value != NULL) {
1236 dict = PyDict_New();
1237 if (dict == NULL)
1238 return -1;
1239 *dictptr = dict;
1240 }
1241 if (dict != NULL) {
1242 int res;
1243 if (value == NULL)
1244 res = PyDict_DelItem(dict, name);
1245 else
1246 res = PyDict_SetItem(dict, name, value);
1247 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1248 PyErr_SetObject(PyExc_AttributeError, name);
1249 return res;
1250 }
1251 }
1252
1253 if (f != NULL)
1254 return f(descr, obj, value);
1255
1256 if (descr == NULL) {
1257 PyErr_Format(PyExc_AttributeError,
1258 "'%.50s' object has no attribute '%.400s'",
1259 tp->tp_name, PyString_AS_STRING(name));
1260 return -1;
1261 }
1262
1263 PyErr_Format(PyExc_AttributeError,
1264 "'%.50s' object attribute '%.400s' is read-only",
1265 tp->tp_name, PyString_AS_STRING(name));
1266 return -1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001267}
1268
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001269/* Test a value used as condition, e.g., in a for or if statement.
1270 Return -1 if an error occurred */
1271
1272int
Fred Drake100814d2000-07-09 15:48:49 +00001273PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001274{
1275 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001276 if (v == Py_None)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001277 res = 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001278 else if (v->ob_type->tp_as_number != NULL &&
1279 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001280 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001281 else if (v->ob_type->tp_as_mapping != NULL &&
1282 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001283 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001284 else if (v->ob_type->tp_as_sequence != NULL &&
1285 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001286 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1287 else
1288 res = 1;
1289 if (res > 0)
1290 res = 1;
1291 return res;
1292}
1293
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001294/* equivalent of 'not v'
1295 Return -1 if an error occurred */
1296
1297int
Fred Drake100814d2000-07-09 15:48:49 +00001298PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001299{
1300 int res;
1301 res = PyObject_IsTrue(v);
1302 if (res < 0)
1303 return res;
1304 return res == 0;
1305}
1306
Guido van Rossum5524a591995-01-10 15:26:20 +00001307/* Coerce two numeric types to the "larger" one.
1308 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001309 Return value:
1310 -1 if an error occurred;
1311 0 if the coercion succeeded (and then the reference counts are increased);
1312 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001313*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001314int
Fred Drake100814d2000-07-09 15:48:49 +00001315PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001316{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001317 register PyObject *v = *pv;
1318 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001319 int res;
1320
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001321 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1322 Py_INCREF(v);
1323 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001324 return 0;
1325 }
1326 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1327 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1328 if (res <= 0)
1329 return res;
1330 }
1331 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1332 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1333 if (res <= 0)
1334 return res;
1335 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001336 return 1;
1337}
1338
Guido van Rossume797ec12001-01-17 15:24:28 +00001339/* Coerce two numeric types to the "larger" one.
1340 Increment the reference count on each argument.
1341 Return -1 and raise an exception if no coercion is possible
1342 (and then no reference count is incremented).
1343*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001344int
Fred Drake100814d2000-07-09 15:48:49 +00001345PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001346{
1347 int err = PyNumber_CoerceEx(pv, pw);
1348 if (err <= 0)
1349 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001350 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001351 return -1;
1352}
1353
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001354
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001355/* Test whether an object can be called */
1356
1357int
Fred Drake100814d2000-07-09 15:48:49 +00001358PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001359{
1360 if (x == NULL)
1361 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362 if (PyInstance_Check(x)) {
1363 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001364 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001366 return 0;
1367 }
1368 /* Could test recursively but don't, for fear of endless
1369 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001370 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001371 return 1;
1372 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 else {
1374 return x->ob_type->tp_call != NULL;
1375 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001376}
1377
Tim Peters7eea37e2001-09-04 22:08:56 +00001378/* Helper for PyObject_Dir.
1379 Merge the __dict__ of aclass into dict, and recursively also all
1380 the __dict__s of aclass's base classes. The order of merging isn't
1381 defined, as it's expected that only the final set of dict keys is
1382 interesting.
1383 Return 0 on success, -1 on error.
1384*/
1385
1386static int
1387merge_class_dict(PyObject* dict, PyObject* aclass)
1388{
1389 PyObject *classdict;
1390 PyObject *bases;
1391
1392 assert(PyDict_Check(dict));
1393 assert(aclass);
1394
1395 /* Merge in the type's dict (if any). */
1396 classdict = PyObject_GetAttrString(aclass, "__dict__");
1397 if (classdict == NULL)
1398 PyErr_Clear();
1399 else {
1400 int status = PyDict_Update(dict, classdict);
1401 Py_DECREF(classdict);
1402 if (status < 0)
1403 return -1;
1404 }
1405
1406 /* Recursively merge in the base types' (if any) dicts. */
1407 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001408 if (bases == NULL)
1409 PyErr_Clear();
1410 else {
Tim Peters7eea37e2001-09-04 22:08:56 +00001411 int i, n;
1412 assert(PyTuple_Check(bases));
1413 n = PyTuple_GET_SIZE(bases);
1414 for (i = 0; i < n; i++) {
1415 PyObject *base = PyTuple_GET_ITEM(bases, i);
1416 if (merge_class_dict(dict, base) < 0) {
1417 Py_DECREF(bases);
1418 return -1;
1419 }
1420 }
1421 Py_DECREF(bases);
1422 }
1423 return 0;
1424}
1425
Tim Peters305b5852001-09-17 02:38:46 +00001426/* Helper for PyObject_Dir.
1427 If obj has an attr named attrname that's a list, merge its string
1428 elements into keys of dict.
1429 Return 0 on success, -1 on error. Errors due to not finding the attr,
1430 or the attr not being a list, are suppressed.
1431*/
1432
1433static int
1434merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1435{
1436 PyObject *list;
1437 int result = 0;
1438
1439 assert(PyDict_Check(dict));
1440 assert(obj);
1441 assert(attrname);
1442
1443 list = PyObject_GetAttrString(obj, attrname);
1444 if (list == NULL)
1445 PyErr_Clear();
1446
1447 else if (PyList_Check(list)) {
1448 int i;
1449 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1450 PyObject *item = PyList_GET_ITEM(list, i);
1451 if (PyString_Check(item)) {
1452 result = PyDict_SetItem(dict, item, Py_None);
1453 if (result < 0)
1454 break;
1455 }
1456 }
1457 }
1458
1459 Py_XDECREF(list);
1460 return result;
1461}
1462
Tim Peters7eea37e2001-09-04 22:08:56 +00001463/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1464 docstring, which should be kept in synch with this implementation. */
1465
1466PyObject *
1467PyObject_Dir(PyObject *arg)
1468{
1469 /* Set exactly one of these non-NULL before the end. */
1470 PyObject *result = NULL; /* result list */
1471 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1472
1473 /* If NULL arg, return the locals. */
1474 if (arg == NULL) {
1475 PyObject *locals = PyEval_GetLocals();
1476 if (locals == NULL)
1477 goto error;
1478 result = PyDict_Keys(locals);
1479 if (result == NULL)
1480 goto error;
1481 }
1482
1483 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001484 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001485 masterdict = PyObject_GetAttrString(arg, "__dict__");
1486 if (masterdict == NULL)
1487 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001488 if (!PyDict_Check(masterdict)) {
1489 PyErr_SetString(PyExc_TypeError,
1490 "module.__dict__ is not a dictionary");
1491 goto error;
1492 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001493 }
1494
1495 /* Elif some form of type or class, grab its dict and its bases.
1496 We deliberately don't suck up its __class__, as methods belonging
1497 to the metaclass would probably be more confusing than helpful. */
1498 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1499 masterdict = PyDict_New();
1500 if (masterdict == NULL)
1501 goto error;
1502 if (merge_class_dict(masterdict, arg) < 0)
1503 goto error;
1504 }
1505
1506 /* Else look at its dict, and the attrs reachable from its class. */
1507 else {
1508 PyObject *itsclass;
1509 /* Create a dict to start with. CAUTION: Not everything
1510 responding to __dict__ returns a dict! */
1511 masterdict = PyObject_GetAttrString(arg, "__dict__");
1512 if (masterdict == NULL) {
1513 PyErr_Clear();
1514 masterdict = PyDict_New();
1515 }
1516 else if (!PyDict_Check(masterdict)) {
1517 Py_DECREF(masterdict);
1518 masterdict = PyDict_New();
1519 }
1520 else {
1521 /* The object may have returned a reference to its
1522 dict, so copy it to avoid mutating it. */
1523 PyObject *temp = PyDict_Copy(masterdict);
1524 Py_DECREF(masterdict);
1525 masterdict = temp;
1526 }
1527 if (masterdict == NULL)
1528 goto error;
1529
Tim Peters305b5852001-09-17 02:38:46 +00001530 /* Merge in __members__ and __methods__ (if any).
1531 XXX Would like this to go away someday; for now, it's
1532 XXX needed to get at im_self etc of method objects. */
1533 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1534 goto error;
1535 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1536 goto error;
1537
Tim Peters7eea37e2001-09-04 22:08:56 +00001538 /* Merge in attrs reachable from its class.
1539 CAUTION: Not all objects have a __class__ attr. */
1540 itsclass = PyObject_GetAttrString(arg, "__class__");
1541 if (itsclass == NULL)
1542 PyErr_Clear();
1543 else {
1544 int status = merge_class_dict(masterdict, itsclass);
1545 Py_DECREF(itsclass);
1546 if (status < 0)
1547 goto error;
1548 }
1549 }
1550
1551 assert((result == NULL) ^ (masterdict == NULL));
1552 if (masterdict != NULL) {
1553 /* The result comes from its keys. */
1554 assert(result == NULL);
1555 result = PyDict_Keys(masterdict);
1556 if (result == NULL)
1557 goto error;
1558 }
1559
1560 assert(result);
1561 if (PyList_Sort(result) != 0)
1562 goto error;
1563 else
1564 goto normal_return;
1565
1566 error:
1567 Py_XDECREF(result);
1568 result = NULL;
1569 /* fall through */
1570 normal_return:
1571 Py_XDECREF(masterdict);
1572 return result;
1573}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001574
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001575/*
1576NoObject is usable as a non-NULL undefined value, used by the macro None.
1577There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001578so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001579(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001580*/
1581
Guido van Rossum0c182a11992-03-27 17:26:13 +00001582/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001583static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001584none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001585{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001586 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001587}
1588
Barry Warsaw9bf16442001-01-23 16:24:35 +00001589/* ARGUSED */
1590static void
1591none_dealloc(PyObject* ignore)
1592{
1593 /* This should never get called, but we also don't want to SEGV if
1594 * we accidently decref None out of existance.
1595 */
1596 abort();
1597}
1598
1599
Guido van Rossumba21a492001-08-16 08:17:26 +00001600static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001601 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001602 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001603 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001604 0,
1605 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001606 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001607 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001608 0, /*tp_getattr*/
1609 0, /*tp_setattr*/
1610 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001611 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001612 0, /*tp_as_number*/
1613 0, /*tp_as_sequence*/
1614 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001615 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001616};
1617
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001618PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001619 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001620};
1621
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001622/* NotImplemented is an object that can be used to signal that an
1623 operation is not implemented for the given type combination. */
1624
1625static PyObject *
1626NotImplemented_repr(PyObject *op)
1627{
1628 return PyString_FromString("NotImplemented");
1629}
1630
1631static PyTypeObject PyNotImplemented_Type = {
1632 PyObject_HEAD_INIT(&PyType_Type)
1633 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001634 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001635 0,
1636 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001637 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001638 0, /*tp_print*/
1639 0, /*tp_getattr*/
1640 0, /*tp_setattr*/
1641 0, /*tp_compare*/
1642 (reprfunc)NotImplemented_repr, /*tp_repr*/
1643 0, /*tp_as_number*/
1644 0, /*tp_as_sequence*/
1645 0, /*tp_as_mapping*/
1646 0, /*tp_hash */
1647};
1648
1649PyObject _Py_NotImplementedStruct = {
1650 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1651};
1652
Guido van Rossumba21a492001-08-16 08:17:26 +00001653void
1654_Py_ReadyTypes(void)
1655{
1656 if (PyType_Ready(&PyType_Type) < 0)
1657 Py_FatalError("Can't initialize 'type'");
1658
1659 if (PyType_Ready(&PyList_Type) < 0)
1660 Py_FatalError("Can't initialize 'list'");
1661
1662 if (PyType_Ready(&PyNone_Type) < 0)
1663 Py_FatalError("Can't initialize type(None)");
1664
1665 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1666 Py_FatalError("Can't initialize type(NotImplemented)");
1667}
1668
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001669
Guido van Rossum84a90321996-05-22 16:34:47 +00001670#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001672static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001673
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001674void
Fred Drake100814d2000-07-09 15:48:49 +00001675_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001676{
1677 refchain._ob_prev = refchain._ob_next = &refchain;
1678 _Py_RefTotal = 0;
1679}
1680
1681void
Fred Drake100814d2000-07-09 15:48:49 +00001682_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001683{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001684 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001685 op->ob_refcnt = 1;
1686 op->_ob_next = refchain._ob_next;
1687 op->_ob_prev = &refchain;
1688 refchain._ob_next->_ob_prev = op;
1689 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001690#ifdef COUNT_ALLOCS
1691 inc_count(op->ob_type);
1692#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001693}
1694
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001695void
Fred Drake100814d2000-07-09 15:48:49 +00001696_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001697{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001698#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001699 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001700#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001701 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001702 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001703 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001704 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001705 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001706#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001707 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1708 if (p == op)
1709 break;
1710 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001711 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001712 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001713#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001714 op->_ob_next->_ob_prev = op->_ob_prev;
1715 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001716 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001717#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001718 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001719#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001720}
1721
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001722void
Fred Drake100814d2000-07-09 15:48:49 +00001723_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001724{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001725 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001726 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001727 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001728}
1729
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001730void
Fred Drake100814d2000-07-09 15:48:49 +00001731_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001732{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001733 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001734 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001735 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1736 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001737 if (PyObject_Print(op, fp, 0) != 0)
1738 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001739 putc('\n', fp);
1740 }
1741}
1742
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001743PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001744_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001745{
1746 int i, n;
1747 PyObject *t = NULL;
1748 PyObject *res, *op;
1749
1750 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1751 return NULL;
1752 op = refchain._ob_next;
1753 res = PyList_New(0);
1754 if (res == NULL)
1755 return NULL;
1756 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1757 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001758 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001759 op = op->_ob_next;
1760 if (op == &refchain)
1761 return res;
1762 }
1763 if (PyList_Append(res, op) < 0) {
1764 Py_DECREF(res);
1765 return NULL;
1766 }
1767 op = op->_ob_next;
1768 }
1769 return res;
1770}
1771
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001772#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001773
1774
1775/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001776PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001777
1778
1779/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001780int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001781
1782
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001783/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001784
Thomas Wouters334fb892000-07-25 12:56:38 +00001785void *
Fred Drake100814d2000-07-09 15:48:49 +00001786PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001787{
1788#if _PyMem_EXTRA > 0
1789 if (nbytes == 0)
1790 nbytes = _PyMem_EXTRA;
1791#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001792 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001793}
1794
Thomas Wouters334fb892000-07-25 12:56:38 +00001795void *
1796PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001797{
1798#if _PyMem_EXTRA > 0
1799 if (nbytes == 0)
1800 nbytes = _PyMem_EXTRA;
1801#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001802 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001803}
1804
1805void
Thomas Wouters334fb892000-07-25 12:56:38 +00001806PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001807{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001808 PyMem_FREE(p);
1809}
1810
1811
1812/* Python's object malloc wrappers (see objimpl.h) */
1813
Thomas Wouters334fb892000-07-25 12:56:38 +00001814void *
Fred Drake100814d2000-07-09 15:48:49 +00001815PyObject_Malloc(size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001816{
1817 return PyObject_MALLOC(nbytes);
1818}
1819
Thomas Wouters334fb892000-07-25 12:56:38 +00001820void *
1821PyObject_Realloc(void *p, size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001822{
1823 return PyObject_REALLOC(p, nbytes);
1824}
1825
1826void
Thomas Wouters334fb892000-07-25 12:56:38 +00001827PyObject_Free(void *p)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001828{
1829 PyObject_FREE(p);
Guido van Rossume09fb551997-08-05 02:04:34 +00001830}
Guido van Rossum86610361998-04-10 22:32:46 +00001831
1832
1833/* These methods are used to control infinite recursion in repr, str, print,
1834 etc. Container objects that may recursively contain themselves,
1835 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1836 Py_ReprLeave() to avoid infinite recursion.
1837
1838 Py_ReprEnter() returns 0 the first time it is called for a particular
1839 object and 1 every time thereafter. It returns -1 if an exception
1840 occurred. Py_ReprLeave() has no return value.
1841
1842 See dictobject.c and listobject.c for examples of use.
1843*/
1844
1845#define KEY "Py_Repr"
1846
1847int
Fred Drake100814d2000-07-09 15:48:49 +00001848Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001849{
1850 PyObject *dict;
1851 PyObject *list;
1852 int i;
1853
1854 dict = PyThreadState_GetDict();
1855 if (dict == NULL)
1856 return -1;
1857 list = PyDict_GetItemString(dict, KEY);
1858 if (list == NULL) {
1859 list = PyList_New(0);
1860 if (list == NULL)
1861 return -1;
1862 if (PyDict_SetItemString(dict, KEY, list) < 0)
1863 return -1;
1864 Py_DECREF(list);
1865 }
1866 i = PyList_GET_SIZE(list);
1867 while (--i >= 0) {
1868 if (PyList_GET_ITEM(list, i) == obj)
1869 return 1;
1870 }
1871 PyList_Append(list, obj);
1872 return 0;
1873}
1874
1875void
Fred Drake100814d2000-07-09 15:48:49 +00001876Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001877{
1878 PyObject *dict;
1879 PyObject *list;
1880 int i;
1881
1882 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001883 if (dict == NULL)
1884 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001885 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001886 if (list == NULL || !PyList_Check(list))
1887 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001888 i = PyList_GET_SIZE(list);
1889 /* Count backwards because we always expect obj to be list[-1] */
1890 while (--i >= 0) {
1891 if (PyList_GET_ITEM(list, i) == obj) {
1892 PyList_SetSlice(list, i, i + 1, NULL);
1893 break;
1894 }
1895 }
1896}
Guido van Rossumd724b232000-03-13 16:01:29 +00001897
1898/*
1899 trashcan
1900 CT 2k0130
1901 non-recursively destroy nested objects
1902
1903 CT 2k0223
1904 everything is now done in a macro.
1905
1906 CT 2k0305
1907 modified to use functions, after Tim Peter's suggestion.
1908
1909 CT 2k0309
1910 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001911
1912 CT 2k0325
1913 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00001914
1915 CT 2k0422
1916 complete rewrite. We now build a chain via ob_type
1917 and save the limited number of types in ob_refcnt.
1918 This is perfect since we don't need any memory.
1919 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00001920*/
1921
Guido van Rossume92e6102000-04-24 15:40:53 +00001922#define Py_TRASHCAN_TUPLE 1
1923#define Py_TRASHCAN_LIST 2
1924#define Py_TRASHCAN_DICT 3
1925#define Py_TRASHCAN_FRAME 4
1926#define Py_TRASHCAN_TRACEBACK 5
1927/* extend here if other objects want protection */
1928
Guido van Rossumd724b232000-03-13 16:01:29 +00001929int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001930
Guido van Rossumd724b232000-03-13 16:01:29 +00001931PyObject * _PyTrash_delete_later = NULL;
1932
1933void
Fred Drake100814d2000-07-09 15:48:49 +00001934_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001935{
Guido van Rossume92e6102000-04-24 15:40:53 +00001936 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001937
Guido van Rossume92e6102000-04-24 15:40:53 +00001938 if (PyTuple_Check(op))
1939 typecode = Py_TRASHCAN_TUPLE;
1940 else if (PyList_Check(op))
1941 typecode = Py_TRASHCAN_LIST;
1942 else if (PyDict_Check(op))
1943 typecode = Py_TRASHCAN_DICT;
1944 else if (PyFrame_Check(op))
1945 typecode = Py_TRASHCAN_FRAME;
1946 else if (PyTraceBack_Check(op))
1947 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00001948 else /* We have a bug here -- those are the only types in GC */ {
1949 Py_FatalError("Type not supported in GC -- internal bug");
1950 return; /* pacify compiler -- execution never here */
1951 }
Guido van Rossume92e6102000-04-24 15:40:53 +00001952 op->ob_refcnt = typecode;
Guido van Rossumd724b232000-03-13 16:01:29 +00001953
Guido van Rossume92e6102000-04-24 15:40:53 +00001954 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
1955 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001956}
1957
1958void
Fred Drake100814d2000-07-09 15:48:49 +00001959_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001960{
1961 while (_PyTrash_delete_later) {
1962 PyObject *shredder = _PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001963 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
1964
1965 switch (shredder->ob_refcnt) {
1966 case Py_TRASHCAN_TUPLE:
1967 shredder->ob_type = &PyTuple_Type;
1968 break;
1969 case Py_TRASHCAN_LIST:
1970 shredder->ob_type = &PyList_Type;
1971 break;
1972 case Py_TRASHCAN_DICT:
1973 shredder->ob_type = &PyDict_Type;
1974 break;
1975 case Py_TRASHCAN_FRAME:
1976 shredder->ob_type = &PyFrame_Type;
1977 break;
1978 case Py_TRASHCAN_TRACEBACK:
1979 shredder->ob_type = &PyTraceBack_Type;
1980 break;
1981 }
1982 _Py_NewReference(shredder);
1983
Guido van Rossumd724b232000-03-13 16:01:29 +00001984 ++_PyTrash_delete_nesting;
1985 Py_DECREF(shredder);
1986 --_PyTrash_delete_nesting;
1987 }
1988}
Neil Schemenauera35c6882001-02-27 04:45:05 +00001989
1990#ifdef WITH_PYMALLOC
1991#include "obmalloc.c"
1992#endif