blob: 668bd4f33246fee6957f028877bafce94a0973db [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 Rossumd1f06b92001-01-24 22:14:43 +0000368 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000369 res = (*f)(v, w, op);
370 if (res != Py_NotImplemented)
371 return res;
372 Py_DECREF(res);
373 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000374 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000375 return (*f)(w, v, swapped_op[op]);
376 }
377 res = Py_NotImplemented;
378 Py_INCREF(res);
379 return res;
380}
381
382/* Try a genuine rich comparison, returning an int. Return:
383 -1 for exception (including the case where try_rich_compare() returns an
384 object that's not a Boolean);
385 0 if the outcome is false;
386 1 if the outcome is true;
387 2 if this particular rich comparison is not implemented or undefined.
388*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000389static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000390try_rich_compare_bool(PyObject *v, PyObject *w, int op)
391{
392 PyObject *res;
393 int ok;
394
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000395 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000396 return 2; /* Shortcut, avoid INCREF+DECREF */
397 res = try_rich_compare(v, w, op);
398 if (res == NULL)
399 return -1;
400 if (res == Py_NotImplemented) {
401 Py_DECREF(res);
402 return 2;
403 }
404 ok = PyObject_IsTrue(res);
405 Py_DECREF(res);
406 return ok;
407}
408
409/* Try rich comparisons to determine a 3-way comparison. Return:
410 -2 for an exception;
411 -1 if v < w;
412 0 if v == w;
413 1 if v > w;
414 2 if this particular rich comparison is not implemented or undefined.
415*/
416static int
417try_rich_to_3way_compare(PyObject *v, PyObject *w)
418{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000419 static struct { int op; int outcome; } tries[3] = {
420 /* Try this operator, and if it is true, use this outcome: */
421 {Py_EQ, 0},
422 {Py_LT, -1},
423 {Py_GT, 1},
424 };
425 int i;
426
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000427 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000428 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000429
430 for (i = 0; i < 3; i++) {
431 switch (try_rich_compare_bool(v, w, tries[i].op)) {
432 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000433 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000434 case 1:
435 return tries[i].outcome;
436 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000437 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000438
439 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000440}
441
442/* Try a 3-way comparison, returning an int. Return:
443 -2 for an exception;
444 -1 if v < w;
445 0 if v == w;
446 1 if v > w;
447 2 if this particular 3-way comparison is not implemented or undefined.
448*/
449static int
450try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000451{
452 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000453 cmpfunc f;
454
455 /* Comparisons involving instances are given to instance_compare,
456 which has the same return conventions as this function. */
457
Guido van Rossumab3b0342001-09-18 20:38:53 +0000458 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000459 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000460 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000461 if (PyInstance_Check(w))
462 return (*w->ob_type->tp_compare)(v, w);
463
Guido van Rossumab3b0342001-09-18 20:38:53 +0000464 /* If both have the same (non-NULL) tp_compare, use it. */
465 if (f != NULL && f == w->ob_type->tp_compare) {
466 c = (*f)(v, w);
467 if (c < 0 && PyErr_Occurred())
468 return -1;
469 return c < 0 ? -1 : c > 0 ? 1 : 0;
470 }
471
472 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
473 if (f == _PyObject_SlotCompare ||
474 w->ob_type->tp_compare == _PyObject_SlotCompare)
475 return _PyObject_SlotCompare(v, w);
476
Guido van Rossume797ec12001-01-17 15:24:28 +0000477 /* Try coercion; if it fails, give up */
478 c = PyNumber_CoerceEx(&v, &w);
479 if (c < 0)
480 return -2;
481 if (c > 0)
482 return 2;
483
484 /* Try v's comparison, if defined */
485 if ((f = v->ob_type->tp_compare) != NULL) {
486 c = (*f)(v, w);
487 Py_DECREF(v);
488 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000489 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000490 return -2;
491 return c < 0 ? -1 : c > 0 ? 1 : 0;
492 }
493
494 /* Try w's comparison, if defined */
495 if ((f = w->ob_type->tp_compare) != NULL) {
496 c = (*f)(w, v); /* swapped! */
497 Py_DECREF(v);
498 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000499 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000500 return -2;
501 return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
502 }
503
504 /* No comparison defined */
505 Py_DECREF(v);
506 Py_DECREF(w);
507 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000508}
509
Guido van Rossume797ec12001-01-17 15:24:28 +0000510/* Final fallback 3-way comparison, returning an int. Return:
511 -2 if an error occurred;
512 -1 if v < w;
513 0 if v == w;
514 1 if v > w.
515*/
516static int
517default_3way_compare(PyObject *v, PyObject *w)
518{
519 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000520 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000521
522 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000523 /* When comparing these pointers, they must be cast to
524 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
525 * uintptr_t). ANSI specifies that pointer compares other
526 * than == and != to non-related structures are undefined.
527 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000528 Py_uintptr_t vv = (Py_uintptr_t)v;
529 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000530 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
531 }
532
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000533#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000534 /* Special case for Unicode */
535 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
536 c = PyUnicode_Compare(v, w);
537 if (!PyErr_Occurred())
538 return c;
539 /* TypeErrors are ignored: if Unicode coercion fails due
540 to one of the arguments not having the right type, we
541 continue as defined by the coercion protocol (see
542 above). Luckily, decoding errors are reported as
543 ValueErrors and are not masked by this technique. */
544 if (!PyErr_ExceptionMatches(PyExc_TypeError))
545 return -2;
546 PyErr_Clear();
547 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000548#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000549
Guido van Rossum0871e932001-01-22 19:28:09 +0000550 /* None is smaller than anything */
551 if (v == Py_None)
552 return -1;
553 if (w == Py_None)
554 return 1;
555
Guido van Rossume797ec12001-01-17 15:24:28 +0000556 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000557 if (v->ob_type->tp_as_number)
558 vname = "";
559 else
560 vname = v->ob_type->tp_name;
561 if (w->ob_type->tp_as_number)
562 wname = "";
563 else
564 wname = w->ob_type->tp_name;
565 c = strcmp(vname, wname);
566 if (c < 0)
567 return -1;
568 if (c > 0)
569 return 1;
570 /* Same type name, or (more likely) incomparable numeric types */
571 return ((Py_uintptr_t)(v->ob_type) < (
572 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000573}
574
575#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
576
Tim Peters6d60b2e2001-05-07 20:53:51 +0000577/* Do a 3-way comparison, by hook or by crook. Return:
578 -2 for an exception;
579 -1 if v < w;
580 0 if v == w;
581 1 if v > w;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000582 If the object implements a tp_compare function, it returns
583 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000584*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000585static int
Fred Drake100814d2000-07-09 15:48:49 +0000586do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000587{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000588 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000589 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000590
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000591 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000592 && (f = v->ob_type->tp_compare) != NULL) {
593 c = (*f)(v, w);
594 if (c != 2 || !PyInstance_Check(v))
595 return c;
596 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000597 c = try_rich_to_3way_compare(v, w);
598 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000599 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000600 c = try_3way_compare(v, w);
601 if (c < 2)
602 return c;
603 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000604}
605
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000606/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000607 some types) and decremented on exit. If the count exceeds the
608 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000609
610 This is a tunable parameter that should only affect the performance
611 of comparisons, nothing else. Setting it high makes comparing deeply
612 nested non-cyclical data structures faster, but makes comparing cyclical
613 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000614*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000615#define NESTING_LIMIT 20
616
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000617static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000618
619static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000620get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000621{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000622 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000623 PyObject *tstate_dict, *inprogress;
624
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000625 if (key == NULL) {
626 key = PyString_InternFromString("cmp_state");
627 if (key == NULL)
628 return NULL;
629 }
630
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000631 tstate_dict = PyThreadState_GetDict();
632 if (tstate_dict == NULL) {
633 PyErr_BadInternalCall();
634 return NULL;
635 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000636
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000637 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000638 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000639 inprogress = PyDict_New();
640 if (inprogress == NULL)
641 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000642 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000643 Py_DECREF(inprogress);
644 return NULL;
645 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000646 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000647 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000648
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000649 return inprogress;
650}
651
652static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000653check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000654{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000655 PyObject *inprogress;
656 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000657 Py_uintptr_t iv = (Py_uintptr_t)v;
658 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000659 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000660
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000661 inprogress = get_inprogress_dict();
662 if (inprogress == NULL)
663 return NULL;
664
665 token = PyTuple_New(3);
666 if (token == NULL)
667 return NULL;
668
669 if (iv <= iw) {
670 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
671 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
672 if (op >= 0)
673 op = swapped_op[op];
674 } else {
675 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
676 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
677 }
678 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
679 if (x == NULL || y == NULL || z == NULL) {
680 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000681 return NULL;
682 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000683
684 if (PyDict_GetItem(inprogress, token) != NULL) {
685 Py_DECREF(token);
686 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000687 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000688
689 if (PyDict_SetItem(inprogress, token, token) < 0) {
690 Py_DECREF(token);
691 return NULL;
692 }
693
694 return token;
695}
696
697static void
698delete_token(PyObject *token)
699{
700 PyObject *inprogress;
701
702 if (token == NULL || token == Py_None)
703 return;
704 inprogress = get_inprogress_dict();
705 if (inprogress == NULL)
706 PyErr_Clear();
707 else
708 PyDict_DelItem(inprogress, token);
709 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000710}
711
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712int
Fred Drake100814d2000-07-09 15:48:49 +0000713PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000714{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000715 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000716 int result;
717
Jack Jansend49cbe12000-08-22 21:52:51 +0000718#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000719 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000720 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
721 return -1;
722 }
723#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000724 if (v == NULL || w == NULL) {
725 PyErr_BadInternalCall();
726 return -1;
727 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728 if (v == w)
729 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000730 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000731 compare_nesting++;
732 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000733 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000734 || (vtp->tp_as_sequence
735 && !PyString_Check(v)
736 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000737 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000738 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000739
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000740 if (token == NULL) {
741 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000742 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000743 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000744 /* already comparing these objects. assume
745 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000746 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000747 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000748 else {
749 result = do_cmp(v, w);
750 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000751 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000752 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000753 else {
754 result = do_cmp(v, w);
755 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000756 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000757 return result < 0 ? -1 : result;
758}
759
760static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000761convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000762{
Guido van Rossume797ec12001-01-17 15:24:28 +0000763 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000764 switch (op) {
765 case Py_LT: c = c < 0; break;
766 case Py_LE: c = c <= 0; break;
767 case Py_EQ: c = c == 0; break;
768 case Py_NE: c = c != 0; break;
769 case Py_GT: c = c > 0; break;
770 case Py_GE: c = c >= 0; break;
771 }
772 result = c ? Py_True : Py_False;
773 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000774 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000776
777
778static PyObject *
779try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
780{
781 int c;
782
783 c = try_3way_compare(v, w);
784 if (c >= 2)
785 c = default_3way_compare(v, w);
786 if (c <= -2)
787 return NULL;
788 return convert_3way_to_object(op, c);
789}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000790
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000791static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000792do_richcmp(PyObject *v, PyObject *w, int op)
793{
794 PyObject *res;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000795 cmpfunc f;
796
797 /* If the types are equal, don't bother with coercions etc.
798 Instances are special-cased in try_3way_compare, since
799 a result of 2 does *not* mean one value being greater
800 than the other. */
801 if (v->ob_type == w->ob_type
802 && (f = v->ob_type->tp_compare) != NULL
803 && !PyInstance_Check(v)) {
804 int c;
805 richcmpfunc f1;
806 if ((f1 = RICHCOMPARE(v->ob_type)) != NULL) {
807 /* If the type has richcmp, try it first.
808 try_rich_compare would try it two-sided,
809 which is not needed since we've a single
810 type only. */
811 res = (*f1)(v, w, op);
812 if (res != Py_NotImplemented)
813 return res;
814 Py_DECREF(res);
815 }
816 c = (*f)(v, w);
817 if (c < 0 && PyErr_Occurred())
818 return NULL;
819 return convert_3way_to_object(op, c);
820 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000821
822 res = try_rich_compare(v, w, op);
823 if (res != Py_NotImplemented)
824 return res;
825 Py_DECREF(res);
826
827 return try_3way_to_rich_compare(v, w, op);
828}
829
830PyObject *
831PyObject_RichCompare(PyObject *v, PyObject *w, int op)
832{
833 PyObject *res;
834
835 assert(Py_LT <= op && op <= Py_GE);
836
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000837 compare_nesting++;
838 if (compare_nesting > NESTING_LIMIT &&
839 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000840 || (v->ob_type->tp_as_sequence
841 && !PyString_Check(v)
842 && !PyTuple_Check(v)))) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000843 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000844 PyObject *token = check_recursion(v, w, op);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000845
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000846 if (token == NULL) {
847 res = NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000848 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000849 else if (token == Py_None) {
850 /* already comparing these objects with this operator.
851 assume they're equal until shown otherwise */
852 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000853 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000854 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000855 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000856 else {
857 PyErr_SetString(PyExc_ValueError,
858 "can't order recursive values");
859 res = NULL;
860 }
861 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000862 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000863 else {
864 res = do_richcmp(v, w, op);
865 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000866 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000867 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000868 else {
869 res = do_richcmp(v, w, op);
870 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000871 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000872 return res;
873}
874
Tim Petersde9725f2001-05-05 10:06:17 +0000875/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000876int
877PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
878{
879 PyObject *res = PyObject_RichCompare(v, w, op);
880 int ok;
881
882 if (res == NULL)
883 return -1;
884 ok = PyObject_IsTrue(res);
885 Py_DECREF(res);
886 return ok;
887}
Fred Drake13634cf2000-06-29 19:17:04 +0000888
889/* Set of hash utility functions to help maintaining the invariant that
890 iff a==b then hash(a)==hash(b)
891
892 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
893*/
894
895long
Fred Drake100814d2000-07-09 15:48:49 +0000896_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000897{
Tim Peters39dce292000-08-15 03:34:48 +0000898 double intpart, fractpart;
899 int expo;
900 long hipart;
901 long x; /* the final hash value */
902 /* This is designed so that Python numbers of different types
903 * that compare equal hash to the same value; otherwise comparisons
904 * of mapping keys will turn out weird.
905 */
906
907#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
908{
909 extended e;
910 fractpart = modf(v, &e);
911 intpart = e;
912}
913#else
914 fractpart = modf(v, &intpart);
915#endif
916 if (fractpart == 0.0) {
917 /* This must return the same hash as an equal int or long. */
918 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
919 /* Convert to long and use its hash. */
920 PyObject *plong; /* converted to Python long */
921 if (Py_IS_INFINITY(intpart))
922 /* can't convert to long int -- arbitrary */
923 v = v < 0 ? -271828.0 : 314159.0;
924 plong = PyLong_FromDouble(v);
925 if (plong == NULL)
926 return -1;
927 x = PyObject_Hash(plong);
928 Py_DECREF(plong);
929 return x;
930 }
931 /* Fits in a C long == a Python int, so is its own hash. */
932 x = (long)intpart;
933 if (x == -1)
934 x = -2;
935 return x;
936 }
937 /* The fractional part is non-zero, so we don't have to worry about
938 * making this match the hash of some other type.
939 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000940 * Since the VAX D double format has 56 mantissa bits, which is the
941 * most of any double format in use, each of these parts may have as
942 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000943 * So, assuming sizeof(long) >= 4, each part can be broken into two
944 * longs; frexp and multiplication are used to do that.
945 * Also, since the Cray double format has 15 exponent bits, which is
946 * the most of any double format in use, shifting the exponent field
947 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000948 */
Tim Peters39dce292000-08-15 03:34:48 +0000949 v = frexp(v, &expo);
950 v *= 2147483648.0; /* 2**31 */
951 hipart = (long)v; /* take the top 32 bits */
952 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
953 x = hipart + (long)v + (expo << 15);
954 if (x == -1)
955 x = -2;
956 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000957}
958
959long
Fred Drake100814d2000-07-09 15:48:49 +0000960_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000961{
962#if SIZEOF_LONG >= SIZEOF_VOID_P
963 return (long)p;
964#else
965 /* convert to a Python long and hash that */
966 PyObject* longobj;
967 long x;
968
969 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
970 x = -1;
971 goto finally;
972 }
973 x = PyObject_Hash(longobj);
974
975finally:
976 Py_XDECREF(longobj);
977 return x;
978#endif
979}
980
981
Guido van Rossum9bfef441993-03-29 10:43:31 +0000982long
Fred Drake100814d2000-07-09 15:48:49 +0000983PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000984{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000985 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000986 if (tp->tp_hash != NULL)
987 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000988 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000989 return _Py_HashPointer(v); /* Use address as hash value */
990 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000991 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000993 return -1;
994}
995
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000996PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000997PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000998{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000999 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001000
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001002 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 w = PyString_InternFromString(name);
1004 if (w == NULL)
1005 return NULL;
1006 res = PyObject_GetAttr(v, w);
1007 Py_XDECREF(w);
1008 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001009}
1010
1011int
Fred Drake100814d2000-07-09 15:48:49 +00001012PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001013{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001014 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001015 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001016 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001017 return 1;
1018 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001020 return 0;
1021}
1022
1023int
Fred Drake100814d2000-07-09 15:48:49 +00001024PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001025{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001026 PyObject *s;
1027 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001028
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001030 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031 s = PyString_InternFromString(name);
1032 if (s == NULL)
1033 return -1;
1034 res = PyObject_SetAttr(v, s, w);
1035 Py_XDECREF(s);
1036 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001037}
1038
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001039PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001040PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001041{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042 PyTypeObject *tp = v->ob_type;
1043
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001044#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001045 /* The Unicode to string conversion is done here because the
1046 existing tp_getattro slots expect a string object as name
1047 and we wouldn't want to break those. */
1048 if (PyUnicode_Check(name)) {
1049 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1050 if (name == NULL)
1051 return NULL;
1052 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001053#endif
1054
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001055 if (!PyString_Check(name)) {
1056 PyErr_SetString(PyExc_TypeError,
1057 "attribute name must be string");
1058 return NULL;
1059 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001060 if (tp->tp_getattro != NULL)
1061 return (*tp->tp_getattro)(v, name);
1062 if (tp->tp_getattr != NULL)
1063 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1064 PyErr_Format(PyExc_AttributeError,
1065 "'%.50s' object has no attribute '%.400s'",
1066 tp->tp_name, PyString_AS_STRING(name));
1067 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001068}
1069
1070int
Fred Drake100814d2000-07-09 15:48:49 +00001071PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001072{
1073 PyObject *res = PyObject_GetAttr(v, name);
1074 if (res != NULL) {
1075 Py_DECREF(res);
1076 return 1;
1077 }
1078 PyErr_Clear();
1079 return 0;
1080}
1081
1082int
Fred Drake100814d2000-07-09 15:48:49 +00001083PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001084{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001086 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001087
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001088#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001089 /* The Unicode to string conversion is done here because the
1090 existing tp_setattro slots expect a string object as name
1091 and we wouldn't want to break those. */
1092 if (PyUnicode_Check(name)) {
1093 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1094 if (name == NULL)
1095 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001096 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001097 else
1098#endif
1099 if (!PyString_Check(name)){
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001100 PyErr_SetString(PyExc_TypeError,
1101 "attribute name must be string");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001104 else
1105 Py_INCREF(name);
1106
1107 PyString_InternInPlace(&name);
1108 if (tp->tp_setattro != NULL) {
1109 err = (*tp->tp_setattro)(v, name, value);
1110 Py_DECREF(name);
1111 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 if (tp->tp_setattr != NULL) {
1114 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1115 Py_DECREF(name);
1116 return err;
1117 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001118 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1120 PyErr_Format(PyExc_TypeError,
1121 "'%.100s' object has no attributes "
1122 "(%s .%.100s)",
1123 tp->tp_name,
1124 value==NULL ? "del" : "assign to",
1125 PyString_AS_STRING(name));
1126 else
1127 PyErr_Format(PyExc_TypeError,
1128 "'%.100s' object has only read-only attributes "
1129 "(%s .%.100s)",
1130 tp->tp_name,
1131 value==NULL ? "del" : "assign to",
1132 PyString_AS_STRING(name));
1133 return -1;
1134}
1135
1136/* Helper to get a pointer to an object's __dict__ slot, if any */
1137
1138PyObject **
1139_PyObject_GetDictPtr(PyObject *obj)
1140{
1141#define PTRSIZE (sizeof(PyObject *))
1142
1143 long dictoffset;
1144 PyTypeObject *tp = obj->ob_type;
1145
1146 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1147 return NULL;
1148 dictoffset = tp->tp_dictoffset;
1149 if (dictoffset == 0)
1150 return NULL;
1151 if (dictoffset < 0) {
Neil Schemenauerfd343692001-08-29 23:54:03 +00001152 dictoffset += tp->tp_basicsize;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 assert(dictoffset > 0); /* Sanity check */
1154 if (tp->tp_itemsize > 0) {
1155 int n = ((PyVarObject *)obj)->ob_size;
1156 if (n > 0) {
1157 dictoffset += tp->tp_itemsize * n;
1158 /* Round up, if necessary */
1159 if (tp->tp_itemsize % PTRSIZE != 0) {
1160 dictoffset += PTRSIZE - 1;
1161 dictoffset /= PTRSIZE;
1162 dictoffset *= PTRSIZE;
1163 }
1164 }
1165 }
1166 }
1167 return (PyObject **) ((char *)obj + dictoffset);
1168}
1169
1170/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1171
1172PyObject *
1173PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1174{
1175 PyTypeObject *tp = obj->ob_type;
1176 PyObject *descr;
1177 descrgetfunc f;
1178 PyObject **dictptr;
1179
1180 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001181 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 return NULL;
1183 }
1184
1185 descr = _PyType_Lookup(tp, name);
1186 f = NULL;
1187 if (descr != NULL) {
1188 f = descr->ob_type->tp_descr_get;
1189 if (f != NULL && PyDescr_IsData(descr))
1190 return f(descr, obj, (PyObject *)obj->ob_type);
1191 }
1192
1193 dictptr = _PyObject_GetDictPtr(obj);
1194 if (dictptr != NULL) {
1195 PyObject *dict = *dictptr;
1196 if (dict != NULL) {
1197 PyObject *res = PyDict_GetItem(dict, name);
1198 if (res != NULL) {
1199 Py_INCREF(res);
1200 return res;
1201 }
1202 }
1203 }
1204
1205 if (f != NULL)
1206 return f(descr, obj, (PyObject *)obj->ob_type);
1207
1208 if (descr != NULL) {
1209 Py_INCREF(descr);
1210 return descr;
1211 }
1212
1213 PyErr_Format(PyExc_AttributeError,
1214 "'%.50s' object has no attribute '%.400s'",
1215 tp->tp_name, PyString_AS_STRING(name));
1216 return NULL;
1217}
1218
1219int
1220PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1221{
1222 PyTypeObject *tp = obj->ob_type;
1223 PyObject *descr;
1224 descrsetfunc f;
1225 PyObject **dictptr;
1226
1227 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001228 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229 return -1;
1230 }
1231
1232 descr = _PyType_Lookup(tp, name);
1233 f = NULL;
1234 if (descr != NULL) {
1235 f = descr->ob_type->tp_descr_set;
1236 if (f != NULL && PyDescr_IsData(descr))
1237 return f(descr, obj, value);
1238 }
1239
1240 dictptr = _PyObject_GetDictPtr(obj);
1241 if (dictptr != NULL) {
1242 PyObject *dict = *dictptr;
1243 if (dict == NULL && value != NULL) {
1244 dict = PyDict_New();
1245 if (dict == NULL)
1246 return -1;
1247 *dictptr = dict;
1248 }
1249 if (dict != NULL) {
1250 int res;
1251 if (value == NULL)
1252 res = PyDict_DelItem(dict, name);
1253 else
1254 res = PyDict_SetItem(dict, name, value);
1255 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1256 PyErr_SetObject(PyExc_AttributeError, name);
1257 return res;
1258 }
1259 }
1260
1261 if (f != NULL)
1262 return f(descr, obj, value);
1263
1264 if (descr == NULL) {
1265 PyErr_Format(PyExc_AttributeError,
1266 "'%.50s' object has no attribute '%.400s'",
1267 tp->tp_name, PyString_AS_STRING(name));
1268 return -1;
1269 }
1270
1271 PyErr_Format(PyExc_AttributeError,
1272 "'%.50s' object attribute '%.400s' is read-only",
1273 tp->tp_name, PyString_AS_STRING(name));
1274 return -1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001275}
1276
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001277/* Test a value used as condition, e.g., in a for or if statement.
1278 Return -1 if an error occurred */
1279
1280int
Fred Drake100814d2000-07-09 15:48:49 +00001281PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001282{
1283 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001284 if (v == Py_None)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001285 res = 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001286 else if (v->ob_type->tp_as_number != NULL &&
1287 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001288 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001289 else if (v->ob_type->tp_as_mapping != NULL &&
1290 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001291 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001292 else if (v->ob_type->tp_as_sequence != NULL &&
1293 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001294 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1295 else
1296 res = 1;
1297 if (res > 0)
1298 res = 1;
1299 return res;
1300}
1301
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001302/* equivalent of 'not v'
1303 Return -1 if an error occurred */
1304
1305int
Fred Drake100814d2000-07-09 15:48:49 +00001306PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001307{
1308 int res;
1309 res = PyObject_IsTrue(v);
1310 if (res < 0)
1311 return res;
1312 return res == 0;
1313}
1314
Guido van Rossum5524a591995-01-10 15:26:20 +00001315/* Coerce two numeric types to the "larger" one.
1316 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001317 Return value:
1318 -1 if an error occurred;
1319 0 if the coercion succeeded (and then the reference counts are increased);
1320 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001321*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001322int
Fred Drake100814d2000-07-09 15:48:49 +00001323PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001324{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001325 register PyObject *v = *pv;
1326 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001327 int res;
1328
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001329 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1330 Py_INCREF(v);
1331 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001332 return 0;
1333 }
1334 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1335 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1336 if (res <= 0)
1337 return res;
1338 }
1339 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1340 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1341 if (res <= 0)
1342 return res;
1343 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001344 return 1;
1345}
1346
Guido van Rossume797ec12001-01-17 15:24:28 +00001347/* Coerce two numeric types to the "larger" one.
1348 Increment the reference count on each argument.
1349 Return -1 and raise an exception if no coercion is possible
1350 (and then no reference count is incremented).
1351*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001352int
Fred Drake100814d2000-07-09 15:48:49 +00001353PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001354{
1355 int err = PyNumber_CoerceEx(pv, pw);
1356 if (err <= 0)
1357 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001358 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001359 return -1;
1360}
1361
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001362
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001363/* Test whether an object can be called */
1364
1365int
Fred Drake100814d2000-07-09 15:48:49 +00001366PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001367{
1368 if (x == NULL)
1369 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001370 if (PyInstance_Check(x)) {
1371 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001372 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001374 return 0;
1375 }
1376 /* Could test recursively but don't, for fear of endless
1377 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001378 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001379 return 1;
1380 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 else {
1382 return x->ob_type->tp_call != NULL;
1383 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001384}
1385
Tim Peters7eea37e2001-09-04 22:08:56 +00001386/* Helper for PyObject_Dir.
1387 Merge the __dict__ of aclass into dict, and recursively also all
1388 the __dict__s of aclass's base classes. The order of merging isn't
1389 defined, as it's expected that only the final set of dict keys is
1390 interesting.
1391 Return 0 on success, -1 on error.
1392*/
1393
1394static int
1395merge_class_dict(PyObject* dict, PyObject* aclass)
1396{
1397 PyObject *classdict;
1398 PyObject *bases;
1399
1400 assert(PyDict_Check(dict));
1401 assert(aclass);
1402
1403 /* Merge in the type's dict (if any). */
1404 classdict = PyObject_GetAttrString(aclass, "__dict__");
1405 if (classdict == NULL)
1406 PyErr_Clear();
1407 else {
1408 int status = PyDict_Update(dict, classdict);
1409 Py_DECREF(classdict);
1410 if (status < 0)
1411 return -1;
1412 }
1413
1414 /* Recursively merge in the base types' (if any) dicts. */
1415 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001416 if (bases == NULL)
1417 PyErr_Clear();
1418 else {
Tim Peters7eea37e2001-09-04 22:08:56 +00001419 int i, n;
1420 assert(PyTuple_Check(bases));
1421 n = PyTuple_GET_SIZE(bases);
1422 for (i = 0; i < n; i++) {
1423 PyObject *base = PyTuple_GET_ITEM(bases, i);
1424 if (merge_class_dict(dict, base) < 0) {
1425 Py_DECREF(bases);
1426 return -1;
1427 }
1428 }
1429 Py_DECREF(bases);
1430 }
1431 return 0;
1432}
1433
Tim Peters305b5852001-09-17 02:38:46 +00001434/* Helper for PyObject_Dir.
1435 If obj has an attr named attrname that's a list, merge its string
1436 elements into keys of dict.
1437 Return 0 on success, -1 on error. Errors due to not finding the attr,
1438 or the attr not being a list, are suppressed.
1439*/
1440
1441static int
1442merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1443{
1444 PyObject *list;
1445 int result = 0;
1446
1447 assert(PyDict_Check(dict));
1448 assert(obj);
1449 assert(attrname);
1450
1451 list = PyObject_GetAttrString(obj, attrname);
1452 if (list == NULL)
1453 PyErr_Clear();
1454
1455 else if (PyList_Check(list)) {
1456 int i;
1457 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1458 PyObject *item = PyList_GET_ITEM(list, i);
1459 if (PyString_Check(item)) {
1460 result = PyDict_SetItem(dict, item, Py_None);
1461 if (result < 0)
1462 break;
1463 }
1464 }
1465 }
1466
1467 Py_XDECREF(list);
1468 return result;
1469}
1470
Tim Peters7eea37e2001-09-04 22:08:56 +00001471/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1472 docstring, which should be kept in synch with this implementation. */
1473
1474PyObject *
1475PyObject_Dir(PyObject *arg)
1476{
1477 /* Set exactly one of these non-NULL before the end. */
1478 PyObject *result = NULL; /* result list */
1479 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1480
1481 /* If NULL arg, return the locals. */
1482 if (arg == NULL) {
1483 PyObject *locals = PyEval_GetLocals();
1484 if (locals == NULL)
1485 goto error;
1486 result = PyDict_Keys(locals);
1487 if (result == NULL)
1488 goto error;
1489 }
1490
1491 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001492 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001493 masterdict = PyObject_GetAttrString(arg, "__dict__");
1494 if (masterdict == NULL)
1495 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001496 if (!PyDict_Check(masterdict)) {
1497 PyErr_SetString(PyExc_TypeError,
1498 "module.__dict__ is not a dictionary");
1499 goto error;
1500 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001501 }
1502
1503 /* Elif some form of type or class, grab its dict and its bases.
1504 We deliberately don't suck up its __class__, as methods belonging
1505 to the metaclass would probably be more confusing than helpful. */
1506 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1507 masterdict = PyDict_New();
1508 if (masterdict == NULL)
1509 goto error;
1510 if (merge_class_dict(masterdict, arg) < 0)
1511 goto error;
1512 }
1513
1514 /* Else look at its dict, and the attrs reachable from its class. */
1515 else {
1516 PyObject *itsclass;
1517 /* Create a dict to start with. CAUTION: Not everything
1518 responding to __dict__ returns a dict! */
1519 masterdict = PyObject_GetAttrString(arg, "__dict__");
1520 if (masterdict == NULL) {
1521 PyErr_Clear();
1522 masterdict = PyDict_New();
1523 }
1524 else if (!PyDict_Check(masterdict)) {
1525 Py_DECREF(masterdict);
1526 masterdict = PyDict_New();
1527 }
1528 else {
1529 /* The object may have returned a reference to its
1530 dict, so copy it to avoid mutating it. */
1531 PyObject *temp = PyDict_Copy(masterdict);
1532 Py_DECREF(masterdict);
1533 masterdict = temp;
1534 }
1535 if (masterdict == NULL)
1536 goto error;
1537
Tim Peters305b5852001-09-17 02:38:46 +00001538 /* Merge in __members__ and __methods__ (if any).
1539 XXX Would like this to go away someday; for now, it's
1540 XXX needed to get at im_self etc of method objects. */
1541 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1542 goto error;
1543 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1544 goto error;
1545
Tim Peters7eea37e2001-09-04 22:08:56 +00001546 /* Merge in attrs reachable from its class.
1547 CAUTION: Not all objects have a __class__ attr. */
1548 itsclass = PyObject_GetAttrString(arg, "__class__");
1549 if (itsclass == NULL)
1550 PyErr_Clear();
1551 else {
1552 int status = merge_class_dict(masterdict, itsclass);
1553 Py_DECREF(itsclass);
1554 if (status < 0)
1555 goto error;
1556 }
1557 }
1558
1559 assert((result == NULL) ^ (masterdict == NULL));
1560 if (masterdict != NULL) {
1561 /* The result comes from its keys. */
1562 assert(result == NULL);
1563 result = PyDict_Keys(masterdict);
1564 if (result == NULL)
1565 goto error;
1566 }
1567
1568 assert(result);
1569 if (PyList_Sort(result) != 0)
1570 goto error;
1571 else
1572 goto normal_return;
1573
1574 error:
1575 Py_XDECREF(result);
1576 result = NULL;
1577 /* fall through */
1578 normal_return:
1579 Py_XDECREF(masterdict);
1580 return result;
1581}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001582
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001583/*
1584NoObject is usable as a non-NULL undefined value, used by the macro None.
1585There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001586so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001587(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001588*/
1589
Guido van Rossum0c182a11992-03-27 17:26:13 +00001590/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001591static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001592none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001593{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001594 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001595}
1596
Barry Warsaw9bf16442001-01-23 16:24:35 +00001597/* ARGUSED */
1598static void
1599none_dealloc(PyObject* ignore)
1600{
1601 /* This should never get called, but we also don't want to SEGV if
1602 * we accidently decref None out of existance.
1603 */
1604 abort();
1605}
1606
1607
Guido van Rossumba21a492001-08-16 08:17:26 +00001608static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001609 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001610 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001611 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001612 0,
1613 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001614 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001615 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001616 0, /*tp_getattr*/
1617 0, /*tp_setattr*/
1618 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001619 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001620 0, /*tp_as_number*/
1621 0, /*tp_as_sequence*/
1622 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001623 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001624};
1625
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001626PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001627 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001628};
1629
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001630/* NotImplemented is an object that can be used to signal that an
1631 operation is not implemented for the given type combination. */
1632
1633static PyObject *
1634NotImplemented_repr(PyObject *op)
1635{
1636 return PyString_FromString("NotImplemented");
1637}
1638
1639static PyTypeObject PyNotImplemented_Type = {
1640 PyObject_HEAD_INIT(&PyType_Type)
1641 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001642 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001643 0,
1644 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001645 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001646 0, /*tp_print*/
1647 0, /*tp_getattr*/
1648 0, /*tp_setattr*/
1649 0, /*tp_compare*/
1650 (reprfunc)NotImplemented_repr, /*tp_repr*/
1651 0, /*tp_as_number*/
1652 0, /*tp_as_sequence*/
1653 0, /*tp_as_mapping*/
1654 0, /*tp_hash */
1655};
1656
1657PyObject _Py_NotImplementedStruct = {
1658 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1659};
1660
Guido van Rossumba21a492001-08-16 08:17:26 +00001661void
1662_Py_ReadyTypes(void)
1663{
1664 if (PyType_Ready(&PyType_Type) < 0)
1665 Py_FatalError("Can't initialize 'type'");
1666
1667 if (PyType_Ready(&PyList_Type) < 0)
1668 Py_FatalError("Can't initialize 'list'");
1669
1670 if (PyType_Ready(&PyNone_Type) < 0)
1671 Py_FatalError("Can't initialize type(None)");
1672
1673 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1674 Py_FatalError("Can't initialize type(NotImplemented)");
1675}
1676
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001677
Guido van Rossum84a90321996-05-22 16:34:47 +00001678#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001680static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001681
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001682void
Fred Drake100814d2000-07-09 15:48:49 +00001683_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001684{
1685 refchain._ob_prev = refchain._ob_next = &refchain;
1686 _Py_RefTotal = 0;
1687}
1688
1689void
Fred Drake100814d2000-07-09 15:48:49 +00001690_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001691{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001692 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001693 op->ob_refcnt = 1;
1694 op->_ob_next = refchain._ob_next;
1695 op->_ob_prev = &refchain;
1696 refchain._ob_next->_ob_prev = op;
1697 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001698#ifdef COUNT_ALLOCS
1699 inc_count(op->ob_type);
1700#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001701}
1702
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001703void
Fred Drake100814d2000-07-09 15:48:49 +00001704_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001705{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001706#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001707 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001708#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001709 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001710 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001711 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001712 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001713 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001714#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001715 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1716 if (p == op)
1717 break;
1718 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001719 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001720 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001721#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001722 op->_ob_next->_ob_prev = op->_ob_prev;
1723 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001724 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001725#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001726 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001727#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001728}
1729
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001730void
Fred Drake100814d2000-07-09 15:48:49 +00001731_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001732{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001733 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001734 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001735 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001736}
1737
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001738void
Fred Drake100814d2000-07-09 15:48:49 +00001739_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001741 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001742 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001743 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1744 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001745 if (PyObject_Print(op, fp, 0) != 0)
1746 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001747 putc('\n', fp);
1748 }
1749}
1750
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001751PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001752_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001753{
1754 int i, n;
1755 PyObject *t = NULL;
1756 PyObject *res, *op;
1757
1758 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1759 return NULL;
1760 op = refchain._ob_next;
1761 res = PyList_New(0);
1762 if (res == NULL)
1763 return NULL;
1764 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1765 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001766 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001767 op = op->_ob_next;
1768 if (op == &refchain)
1769 return res;
1770 }
1771 if (PyList_Append(res, op) < 0) {
1772 Py_DECREF(res);
1773 return NULL;
1774 }
1775 op = op->_ob_next;
1776 }
1777 return res;
1778}
1779
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001780#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001781
1782
1783/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001784PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001785
1786
1787/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001788int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001789
1790
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001791/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001792
Thomas Wouters334fb892000-07-25 12:56:38 +00001793void *
Fred Drake100814d2000-07-09 15:48:49 +00001794PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001795{
1796#if _PyMem_EXTRA > 0
1797 if (nbytes == 0)
1798 nbytes = _PyMem_EXTRA;
1799#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001800 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001801}
1802
Thomas Wouters334fb892000-07-25 12:56:38 +00001803void *
1804PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001805{
1806#if _PyMem_EXTRA > 0
1807 if (nbytes == 0)
1808 nbytes = _PyMem_EXTRA;
1809#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001810 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001811}
1812
1813void
Thomas Wouters334fb892000-07-25 12:56:38 +00001814PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001815{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001816 PyMem_FREE(p);
1817}
1818
1819
1820/* Python's object malloc wrappers (see objimpl.h) */
1821
Thomas Wouters334fb892000-07-25 12:56:38 +00001822void *
Fred Drake100814d2000-07-09 15:48:49 +00001823PyObject_Malloc(size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001824{
1825 return PyObject_MALLOC(nbytes);
1826}
1827
Thomas Wouters334fb892000-07-25 12:56:38 +00001828void *
1829PyObject_Realloc(void *p, size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001830{
1831 return PyObject_REALLOC(p, nbytes);
1832}
1833
1834void
Thomas Wouters334fb892000-07-25 12:56:38 +00001835PyObject_Free(void *p)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001836{
1837 PyObject_FREE(p);
Guido van Rossume09fb551997-08-05 02:04:34 +00001838}
Guido van Rossum86610361998-04-10 22:32:46 +00001839
1840
Fred Drake41deb1e2001-02-01 05:27:45 +00001841/* Hook to clear up weak references only once the _weakref module is
1842 imported. We use a dummy implementation to simplify the code at each
1843 call site instead of requiring a test for NULL.
1844*/
1845
Fred Drakeb60654b2001-02-26 18:56:37 +00001846static void
Fred Drake41deb1e2001-02-01 05:27:45 +00001847empty_clear_weak_refs(PyObject *o)
1848{
Fred Drakeb60654b2001-02-26 18:56:37 +00001849 return;
Fred Drake41deb1e2001-02-01 05:27:45 +00001850}
1851
Fred Drakeb60654b2001-02-26 18:56:37 +00001852void (*PyObject_ClearWeakRefs)(PyObject *) = empty_clear_weak_refs;
Fred Drake41deb1e2001-02-01 05:27:45 +00001853
1854
1855
Guido van Rossum86610361998-04-10 22:32:46 +00001856/* These methods are used to control infinite recursion in repr, str, print,
1857 etc. Container objects that may recursively contain themselves,
1858 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1859 Py_ReprLeave() to avoid infinite recursion.
1860
1861 Py_ReprEnter() returns 0 the first time it is called for a particular
1862 object and 1 every time thereafter. It returns -1 if an exception
1863 occurred. Py_ReprLeave() has no return value.
1864
1865 See dictobject.c and listobject.c for examples of use.
1866*/
1867
1868#define KEY "Py_Repr"
1869
1870int
Fred Drake100814d2000-07-09 15:48:49 +00001871Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001872{
1873 PyObject *dict;
1874 PyObject *list;
1875 int i;
1876
1877 dict = PyThreadState_GetDict();
1878 if (dict == NULL)
1879 return -1;
1880 list = PyDict_GetItemString(dict, KEY);
1881 if (list == NULL) {
1882 list = PyList_New(0);
1883 if (list == NULL)
1884 return -1;
1885 if (PyDict_SetItemString(dict, KEY, list) < 0)
1886 return -1;
1887 Py_DECREF(list);
1888 }
1889 i = PyList_GET_SIZE(list);
1890 while (--i >= 0) {
1891 if (PyList_GET_ITEM(list, i) == obj)
1892 return 1;
1893 }
1894 PyList_Append(list, obj);
1895 return 0;
1896}
1897
1898void
Fred Drake100814d2000-07-09 15:48:49 +00001899Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001900{
1901 PyObject *dict;
1902 PyObject *list;
1903 int i;
1904
1905 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001906 if (dict == NULL)
1907 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001908 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001909 if (list == NULL || !PyList_Check(list))
1910 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001911 i = PyList_GET_SIZE(list);
1912 /* Count backwards because we always expect obj to be list[-1] */
1913 while (--i >= 0) {
1914 if (PyList_GET_ITEM(list, i) == obj) {
1915 PyList_SetSlice(list, i, i + 1, NULL);
1916 break;
1917 }
1918 }
1919}
Guido van Rossumd724b232000-03-13 16:01:29 +00001920
1921/*
1922 trashcan
1923 CT 2k0130
1924 non-recursively destroy nested objects
1925
1926 CT 2k0223
1927 everything is now done in a macro.
1928
1929 CT 2k0305
1930 modified to use functions, after Tim Peter's suggestion.
1931
1932 CT 2k0309
1933 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001934
1935 CT 2k0325
1936 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00001937
1938 CT 2k0422
1939 complete rewrite. We now build a chain via ob_type
1940 and save the limited number of types in ob_refcnt.
1941 This is perfect since we don't need any memory.
1942 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00001943*/
1944
Guido van Rossume92e6102000-04-24 15:40:53 +00001945#define Py_TRASHCAN_TUPLE 1
1946#define Py_TRASHCAN_LIST 2
1947#define Py_TRASHCAN_DICT 3
1948#define Py_TRASHCAN_FRAME 4
1949#define Py_TRASHCAN_TRACEBACK 5
1950/* extend here if other objects want protection */
1951
Guido van Rossumd724b232000-03-13 16:01:29 +00001952int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001953
Guido van Rossumd724b232000-03-13 16:01:29 +00001954PyObject * _PyTrash_delete_later = NULL;
1955
1956void
Fred Drake100814d2000-07-09 15:48:49 +00001957_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001958{
Guido van Rossume92e6102000-04-24 15:40:53 +00001959 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001960
Guido van Rossume92e6102000-04-24 15:40:53 +00001961 if (PyTuple_Check(op))
1962 typecode = Py_TRASHCAN_TUPLE;
1963 else if (PyList_Check(op))
1964 typecode = Py_TRASHCAN_LIST;
1965 else if (PyDict_Check(op))
1966 typecode = Py_TRASHCAN_DICT;
1967 else if (PyFrame_Check(op))
1968 typecode = Py_TRASHCAN_FRAME;
1969 else if (PyTraceBack_Check(op))
1970 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00001971 else /* We have a bug here -- those are the only types in GC */ {
1972 Py_FatalError("Type not supported in GC -- internal bug");
1973 return; /* pacify compiler -- execution never here */
1974 }
Guido van Rossume92e6102000-04-24 15:40:53 +00001975 op->ob_refcnt = typecode;
Guido van Rossumd724b232000-03-13 16:01:29 +00001976
Guido van Rossume92e6102000-04-24 15:40:53 +00001977 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
1978 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001979}
1980
1981void
Fred Drake100814d2000-07-09 15:48:49 +00001982_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001983{
1984 while (_PyTrash_delete_later) {
1985 PyObject *shredder = _PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001986 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
1987
1988 switch (shredder->ob_refcnt) {
1989 case Py_TRASHCAN_TUPLE:
1990 shredder->ob_type = &PyTuple_Type;
1991 break;
1992 case Py_TRASHCAN_LIST:
1993 shredder->ob_type = &PyList_Type;
1994 break;
1995 case Py_TRASHCAN_DICT:
1996 shredder->ob_type = &PyDict_Type;
1997 break;
1998 case Py_TRASHCAN_FRAME:
1999 shredder->ob_type = &PyFrame_Type;
2000 break;
2001 case Py_TRASHCAN_TRACEBACK:
2002 shredder->ob_type = &PyTraceBack_Type;
2003 break;
2004 }
2005 _Py_NewReference(shredder);
2006
Guido van Rossumd724b232000-03-13 16:01:29 +00002007 ++_PyTrash_delete_nesting;
2008 Py_DECREF(shredder);
2009 --_PyTrash_delete_nesting;
2010 }
2011}
Neil Schemenauera35c6882001-02-27 04:45:05 +00002012
2013#ifdef WITH_PYMALLOC
2014#include "obmalloc.c"
2015#endif