blob: b1bf2c3cdbdf1b8b3601986849a37f5a2a44bcb5 [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
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000140/* for binary compatibility with 2.2 */
141#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000142void
Fred Drake100814d2000-07-09 15:48:49 +0000143_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000144{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000145 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146}
147
Guido van Rossum90933611991-06-07 16:10:43 +0000148int
Fred Drake100814d2000-07-09 15:48:49 +0000149PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150{
Guido van Rossum278ef591991-07-27 21:40:24 +0000151 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000153 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000154#ifdef USE_STACKCHECK
155 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000156 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000157 return -1;
158 }
159#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000160 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000161 if (op == NULL) {
162 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163 }
Guido van Rossum90933611991-06-07 16:10:43 +0000164 else {
165 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000166 fprintf(fp, "<refcnt %u at %p>",
167 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000168 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000169 PyObject *s;
170 if (flags & Py_PRINT_RAW)
171 s = PyObject_Str(op);
172 else
173 s = PyObject_Repr(op);
174 if (s == NULL)
175 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000176 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000177 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000178 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000179 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000180 }
Guido van Rossum90933611991-06-07 16:10:43 +0000181 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000182 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000183 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000184 if (ret == 0) {
185 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000187 clearerr(fp);
188 ret = -1;
189 }
190 }
191 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192}
193
Barry Warsaw9bf16442001-01-23 16:24:35 +0000194/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Barry Warsawbbd89b62001-01-24 04:18:13 +0000195void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000196{
Barry Warsaweefb1072001-02-22 22:39:18 +0000197 if (op == NULL)
198 fprintf(stderr, "NULL\n");
199 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000200 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000201 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000202 fprintf(stderr, "\n"
203 "type : %s\n"
204 "refcount: %d\n"
205 "address : %p\n",
206 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
207 op->ob_refcnt,
208 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000209 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000210}
Barry Warsaw903138f2001-01-23 16:33:18 +0000211
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000213PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000216 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000217#ifdef USE_STACKCHECK
218 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000219 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000220 return NULL;
221 }
222#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000223 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000224 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000225 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000226 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000227 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000228 else {
229 PyObject *res;
230 res = (*v->ob_type->tp_repr)(v);
231 if (res == NULL)
232 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000233#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000234 if (PyUnicode_Check(res)) {
235 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000236 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000237 Py_DECREF(res);
238 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000239 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000240 else
241 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000242 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000243#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000244 if (!PyString_Check(res)) {
245 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000246 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000247 res->ob_type->tp_name);
248 Py_DECREF(res);
249 return NULL;
250 }
251 return res;
252 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253}
254
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000255PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000256PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000257{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000258 PyObject *res;
259
Guido van Rossumc6004111993-11-05 10:22:19 +0000260 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000261 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000262 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000264 return v;
265 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000266 if (v->ob_type->tp_str == NULL)
267 return PyObject_Repr(v);
268
269 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000270 if (res == NULL)
271 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000272#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000273 if (PyUnicode_Check(res)) {
274 PyObject* str;
275 str = PyUnicode_AsEncodedString(res, NULL, NULL);
276 Py_DECREF(res);
277 if (str)
278 res = str;
279 else
280 return NULL;
281 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000282#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000283 if (!PyString_Check(res)) {
284 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000285 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000286 res->ob_type->tp_name);
287 Py_DECREF(res);
288 return NULL;
289 }
290 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000291}
292
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000293#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000294PyObject *
295PyObject_Unicode(PyObject *v)
296{
297 PyObject *res;
298
299 if (v == NULL)
300 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000301 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000302 Py_INCREF(v);
303 return v;
304 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000305 if (PyUnicode_Check(v)) {
306 /* For a Unicode subtype that's not a Unicode object,
307 return a true Unicode object with the same data. */
308 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
309 PyUnicode_GET_SIZE(v));
310 }
311 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000312 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000313 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000314 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000315 else {
316 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000317 static PyObject *unicodestr;
318 /* XXX As soon as we have a tp_unicode slot, we should
319 check this before trying the __unicode__
320 method. */
321 if (unicodestr == NULL) {
322 unicodestr= PyString_InternFromString(
323 "__unicode__");
324 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000325 return NULL;
326 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000327 func = PyObject_GetAttr(v, unicodestr);
328 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000329 res = PyEval_CallObject(func, (PyObject *)NULL);
330 Py_DECREF(func);
331 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000332 else {
333 PyErr_Clear();
334 if (v->ob_type->tp_str != NULL)
335 res = (*v->ob_type->tp_str)(v);
336 else
337 res = PyObject_Repr(v);
338 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000339 }
340 if (res == NULL)
341 return NULL;
342 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000343 PyObject *str;
344 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000345 Py_DECREF(res);
346 if (str)
347 res = str;
348 else
349 return NULL;
350 }
351 return res;
352}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000353#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000354
355
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000356/* Macro to get the tp_richcompare field of a type if defined */
357#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
358 ? (t)->tp_richcompare : NULL)
359
Guido van Rossume797ec12001-01-17 15:24:28 +0000360/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
361static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000362
Guido van Rossume797ec12001-01-17 15:24:28 +0000363/* Try a genuine rich comparison, returning an object. Return:
364 NULL for exception;
365 NotImplemented if this particular rich comparison is not implemented or
366 undefined;
367 some object not equal to NotImplemented if it is implemented
368 (this latter object may not be a Boolean).
369*/
370static PyObject *
371try_rich_compare(PyObject *v, PyObject *w, int op)
372{
373 richcmpfunc f;
374 PyObject *res;
375
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000376 if (v->ob_type != w->ob_type &&
377 PyType_IsSubtype(w->ob_type, v->ob_type) &&
378 (f = RICHCOMPARE(w->ob_type)) != NULL) {
379 res = (*f)(w, v, swapped_op[op]);
380 if (res != Py_NotImplemented)
381 return res;
382 Py_DECREF(res);
383 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000384 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000385 res = (*f)(v, w, op);
386 if (res != Py_NotImplemented)
387 return res;
388 Py_DECREF(res);
389 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000390 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000391 return (*f)(w, v, swapped_op[op]);
392 }
393 res = Py_NotImplemented;
394 Py_INCREF(res);
395 return res;
396}
397
398/* Try a genuine rich comparison, returning an int. Return:
399 -1 for exception (including the case where try_rich_compare() returns an
400 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000401 0 if the outcome is false;
402 1 if the outcome is true;
403 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000404*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000405static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000406try_rich_compare_bool(PyObject *v, PyObject *w, int op)
407{
408 PyObject *res;
409 int ok;
410
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000411 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000412 return 2; /* Shortcut, avoid INCREF+DECREF */
413 res = try_rich_compare(v, w, op);
414 if (res == NULL)
415 return -1;
416 if (res == Py_NotImplemented) {
417 Py_DECREF(res);
418 return 2;
419 }
420 ok = PyObject_IsTrue(res);
421 Py_DECREF(res);
422 return ok;
423}
424
425/* Try rich comparisons to determine a 3-way comparison. Return:
426 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000427 -1 if v < w;
428 0 if v == w;
429 1 if v > w;
430 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000431*/
432static int
433try_rich_to_3way_compare(PyObject *v, PyObject *w)
434{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000435 static struct { int op; int outcome; } tries[3] = {
436 /* Try this operator, and if it is true, use this outcome: */
437 {Py_EQ, 0},
438 {Py_LT, -1},
439 {Py_GT, 1},
440 };
441 int i;
442
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000443 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000444 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000445
446 for (i = 0; i < 3; i++) {
447 switch (try_rich_compare_bool(v, w, tries[i].op)) {
448 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000449 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000450 case 1:
451 return tries[i].outcome;
452 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000453 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000454
455 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000456}
457
458/* Try a 3-way comparison, returning an int. Return:
459 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000460 -1 if v < w;
461 0 if v == w;
462 1 if v > w;
463 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000464*/
465static int
466try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000467{
468 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000469 cmpfunc f;
470
471 /* Comparisons involving instances are given to instance_compare,
472 which has the same return conventions as this function. */
473
Guido van Rossumab3b0342001-09-18 20:38:53 +0000474 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000475 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000476 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000477 if (PyInstance_Check(w))
478 return (*w->ob_type->tp_compare)(v, w);
479
Guido van Rossumab3b0342001-09-18 20:38:53 +0000480 /* If both have the same (non-NULL) tp_compare, use it. */
481 if (f != NULL && f == w->ob_type->tp_compare) {
482 c = (*f)(v, w);
483 if (c < 0 && PyErr_Occurred())
484 return -1;
485 return c < 0 ? -1 : c > 0 ? 1 : 0;
486 }
487
488 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
489 if (f == _PyObject_SlotCompare ||
490 w->ob_type->tp_compare == _PyObject_SlotCompare)
491 return _PyObject_SlotCompare(v, w);
492
Guido van Rossume797ec12001-01-17 15:24:28 +0000493 /* Try coercion; if it fails, give up */
494 c = PyNumber_CoerceEx(&v, &w);
495 if (c < 0)
496 return -2;
497 if (c > 0)
498 return 2;
499
500 /* Try v's comparison, if defined */
501 if ((f = v->ob_type->tp_compare) != NULL) {
502 c = (*f)(v, w);
503 Py_DECREF(v);
504 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000505 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000506 return -2;
507 return c < 0 ? -1 : c > 0 ? 1 : 0;
508 }
509
510 /* Try w's comparison, if defined */
511 if ((f = w->ob_type->tp_compare) != NULL) {
512 c = (*f)(w, v); /* swapped! */
513 Py_DECREF(v);
514 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000515 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000516 return -2;
517 return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
518 }
519
520 /* No comparison defined */
521 Py_DECREF(v);
522 Py_DECREF(w);
523 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000524}
525
Guido van Rossume797ec12001-01-17 15:24:28 +0000526/* Final fallback 3-way comparison, returning an int. Return:
527 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000528 -1 if v < w;
529 0 if v == w;
530 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000531*/
532static int
533default_3way_compare(PyObject *v, PyObject *w)
534{
535 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000536 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000537
538 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000539 /* When comparing these pointers, they must be cast to
540 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
541 * uintptr_t). ANSI specifies that pointer compares other
542 * than == and != to non-related structures are undefined.
543 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000544 Py_uintptr_t vv = (Py_uintptr_t)v;
545 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000546 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
547 }
548
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000549#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000550 /* Special case for Unicode */
551 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
552 c = PyUnicode_Compare(v, w);
553 if (!PyErr_Occurred())
554 return c;
555 /* TypeErrors are ignored: if Unicode coercion fails due
556 to one of the arguments not having the right type, we
557 continue as defined by the coercion protocol (see
558 above). Luckily, decoding errors are reported as
559 ValueErrors and are not masked by this technique. */
560 if (!PyErr_ExceptionMatches(PyExc_TypeError))
561 return -2;
562 PyErr_Clear();
563 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000564#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000565
Guido van Rossum0871e932001-01-22 19:28:09 +0000566 /* None is smaller than anything */
567 if (v == Py_None)
568 return -1;
569 if (w == Py_None)
570 return 1;
571
Guido van Rossume797ec12001-01-17 15:24:28 +0000572 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000573 if (v->ob_type->tp_as_number)
574 vname = "";
575 else
576 vname = v->ob_type->tp_name;
577 if (w->ob_type->tp_as_number)
578 wname = "";
579 else
580 wname = w->ob_type->tp_name;
581 c = strcmp(vname, wname);
582 if (c < 0)
583 return -1;
584 if (c > 0)
585 return 1;
586 /* Same type name, or (more likely) incomparable numeric types */
587 return ((Py_uintptr_t)(v->ob_type) < (
588 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000589}
590
591#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
592
Tim Peters6d60b2e2001-05-07 20:53:51 +0000593/* Do a 3-way comparison, by hook or by crook. Return:
594 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000595 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000596 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000597 1 if v > w;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000598 If the object implements a tp_compare function, it returns
599 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000600*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000601static int
Fred Drake100814d2000-07-09 15:48:49 +0000602do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000603{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000604 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000605 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000606
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000607 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000608 && (f = v->ob_type->tp_compare) != NULL) {
609 c = (*f)(v, w);
610 if (c != 2 || !PyInstance_Check(v))
611 return c;
612 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000613 c = try_rich_to_3way_compare(v, w);
614 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000615 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000616 c = try_3way_compare(v, w);
617 if (c < 2)
618 return c;
619 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000620}
621
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000622/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000623 some types) and decremented on exit. If the count exceeds the
624 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000625
626 This is a tunable parameter that should only affect the performance
627 of comparisons, nothing else. Setting it high makes comparing deeply
628 nested non-cyclical data structures faster, but makes comparing cyclical
629 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000630*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000631#define NESTING_LIMIT 20
632
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000633static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000634
635static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000636get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000637{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000638 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000639 PyObject *tstate_dict, *inprogress;
640
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000641 if (key == NULL) {
642 key = PyString_InternFromString("cmp_state");
643 if (key == NULL)
644 return NULL;
645 }
646
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000647 tstate_dict = PyThreadState_GetDict();
648 if (tstate_dict == NULL) {
649 PyErr_BadInternalCall();
650 return NULL;
651 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000652
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000653 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000654 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000655 inprogress = PyDict_New();
656 if (inprogress == NULL)
657 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000658 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000659 Py_DECREF(inprogress);
660 return NULL;
661 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000662 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000663 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000664
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000665 return inprogress;
666}
667
668static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000669check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000670{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000671 PyObject *inprogress;
672 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000673 Py_uintptr_t iv = (Py_uintptr_t)v;
674 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000675 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000676
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000677 inprogress = get_inprogress_dict();
678 if (inprogress == NULL)
679 return NULL;
680
681 token = PyTuple_New(3);
682 if (token == NULL)
683 return NULL;
684
685 if (iv <= iw) {
686 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
687 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
688 if (op >= 0)
689 op = swapped_op[op];
690 } else {
691 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
692 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
693 }
694 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
695 if (x == NULL || y == NULL || z == NULL) {
696 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000697 return NULL;
698 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000699
700 if (PyDict_GetItem(inprogress, token) != NULL) {
701 Py_DECREF(token);
702 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000703 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000704
705 if (PyDict_SetItem(inprogress, token, token) < 0) {
706 Py_DECREF(token);
707 return NULL;
708 }
709
710 return token;
711}
712
713static void
714delete_token(PyObject *token)
715{
716 PyObject *inprogress;
717
718 if (token == NULL || token == Py_None)
719 return;
720 inprogress = get_inprogress_dict();
721 if (inprogress == NULL)
722 PyErr_Clear();
723 else
724 PyDict_DelItem(inprogress, token);
725 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000726}
727
Tim Petersc99213f2001-11-04 05:57:16 +0000728/* Compare v to w. Return
729 -1 if v < w or exception (PyErr_Occurred() true in latter case).
730 0 if v == w.
731 1 if v > w.
732 XXX The docs (C API manual) say the return value is undefined in case
733 XXX of error.
734*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000735int
Fred Drake100814d2000-07-09 15:48:49 +0000736PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000738 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000739 int result;
740
Jack Jansend49cbe12000-08-22 21:52:51 +0000741#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000742 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000743 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000744 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000745 }
746#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000747 if (v == NULL || w == NULL) {
748 PyErr_BadInternalCall();
749 return -1;
750 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000751 if (v == w)
752 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000753 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000754 compare_nesting++;
755 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000756 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000757 || (vtp->tp_as_sequence
758 && !PyString_Check(v)
759 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000760 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000761 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000762
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000763 if (token == NULL) {
764 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000765 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000766 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000767 /* already comparing these objects. assume
768 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000769 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000770 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000771 else {
772 result = do_cmp(v, w);
773 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000774 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000775 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000776 else {
777 result = do_cmp(v, w);
778 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000779 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000780 return result < 0 ? -1 : result;
781}
782
Tim Petersc99213f2001-11-04 05:57:16 +0000783/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000784static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000785convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000786{
Guido van Rossume797ec12001-01-17 15:24:28 +0000787 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000788 switch (op) {
789 case Py_LT: c = c < 0; break;
790 case Py_LE: c = c <= 0; break;
791 case Py_EQ: c = c == 0; break;
792 case Py_NE: c = c != 0; break;
793 case Py_GT: c = c > 0; break;
794 case Py_GE: c = c >= 0; break;
795 }
796 result = c ? Py_True : Py_False;
797 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000798 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000800
Tim Petersc99213f2001-11-04 05:57:16 +0000801/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
802 Return
803 NULL if error
804 Py_True if v op w
805 Py_False if not (v op w)
806*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000807static PyObject *
808try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
809{
810 int c;
811
812 c = try_3way_compare(v, w);
813 if (c >= 2)
814 c = default_3way_compare(v, w);
815 if (c <= -2)
816 return NULL;
817 return convert_3way_to_object(op, c);
818}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819
Tim Petersc99213f2001-11-04 05:57:16 +0000820/* Do rich comparison on v and w. Return
821 NULL if error
822 Else a new reference to an object other than Py_NotImplemented, usually(?):
823 Py_True if v op w
824 Py_False if not (v op w)
825*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000826static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000827do_richcmp(PyObject *v, PyObject *w, int op)
828{
829 PyObject *res;
830
831 res = try_rich_compare(v, w, op);
832 if (res != Py_NotImplemented)
833 return res;
834 Py_DECREF(res);
835
836 return try_3way_to_rich_compare(v, w, op);
837}
838
Tim Petersc99213f2001-11-04 05:57:16 +0000839/* Return:
840 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000841 some object not equal to NotImplemented if it is implemented
842 (this latter object may not be a Boolean).
843*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000844PyObject *
845PyObject_RichCompare(PyObject *v, PyObject *w, int op)
846{
847 PyObject *res;
848
849 assert(Py_LT <= op && op <= Py_GE);
850
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000851 compare_nesting++;
852 if (compare_nesting > NESTING_LIMIT &&
853 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000854 || (v->ob_type->tp_as_sequence
855 && !PyString_Check(v)
856 && !PyTuple_Check(v)))) {
Tim Peters67754e92001-11-04 07:29:31 +0000857
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000858 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000859 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000860 if (token == NULL) {
861 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000862 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000863 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000864 else if (token == Py_None) {
865 /* already comparing these objects with this operator.
866 assume they're equal until shown otherwise */
867 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000868 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000869 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000870 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000871 else {
872 PyErr_SetString(PyExc_ValueError,
873 "can't order recursive values");
874 res = NULL;
875 }
876 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000877 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000878 else {
879 res = do_richcmp(v, w, op);
880 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000881 }
Tim Peters67754e92001-11-04 07:29:31 +0000882 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000883 }
Tim Peters67754e92001-11-04 07:29:31 +0000884
885 /* No nesting extremism.
886 If the types are equal, and not old-style instances, try to
887 get out cheap (don't bother with coercions etc.). */
888 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
889 cmpfunc fcmp;
890 richcmpfunc frich = RICHCOMPARE(v->ob_type);
891 /* If the type has richcmp, try it first. try_rich_compare
892 tries it two-sided, which is not needed since we've a
893 single type only. */
894 if (frich != NULL) {
895 res = (*frich)(v, w, op);
896 if (res != Py_NotImplemented)
897 goto Done;
898 Py_DECREF(res);
899 }
900 /* No richcmp, or this particular richmp not implemented.
901 Try 3-way cmp. */
902 fcmp = v->ob_type->tp_compare;
903 if (fcmp != NULL) {
904 int c = (*fcmp)(v, w);
905 if (c < 0 && PyErr_Occurred()) {
906 res = NULL;
907 goto Done;
908 }
909 res = convert_3way_to_object(op, c);
910 goto Done;
911 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000912 }
Tim Peters67754e92001-11-04 07:29:31 +0000913
914 /* Fast path not taken, or couldn't deliver a useful result. */
915 res = do_richcmp(v, w, op);
916Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000917 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000918 return res;
919}
920
Tim Petersde9725f2001-05-05 10:06:17 +0000921/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000922int
923PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
924{
925 PyObject *res = PyObject_RichCompare(v, w, op);
926 int ok;
927
928 if (res == NULL)
929 return -1;
930 ok = PyObject_IsTrue(res);
931 Py_DECREF(res);
932 return ok;
933}
Fred Drake13634cf2000-06-29 19:17:04 +0000934
935/* Set of hash utility functions to help maintaining the invariant that
936 iff a==b then hash(a)==hash(b)
937
938 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
939*/
940
941long
Fred Drake100814d2000-07-09 15:48:49 +0000942_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000943{
Tim Peters39dce292000-08-15 03:34:48 +0000944 double intpart, fractpart;
945 int expo;
946 long hipart;
947 long x; /* the final hash value */
948 /* This is designed so that Python numbers of different types
949 * that compare equal hash to the same value; otherwise comparisons
950 * of mapping keys will turn out weird.
951 */
952
953#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
954{
955 extended e;
956 fractpart = modf(v, &e);
957 intpart = e;
958}
959#else
960 fractpart = modf(v, &intpart);
961#endif
962 if (fractpart == 0.0) {
963 /* This must return the same hash as an equal int or long. */
964 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
965 /* Convert to long and use its hash. */
966 PyObject *plong; /* converted to Python long */
967 if (Py_IS_INFINITY(intpart))
968 /* can't convert to long int -- arbitrary */
969 v = v < 0 ? -271828.0 : 314159.0;
970 plong = PyLong_FromDouble(v);
971 if (plong == NULL)
972 return -1;
973 x = PyObject_Hash(plong);
974 Py_DECREF(plong);
975 return x;
976 }
977 /* Fits in a C long == a Python int, so is its own hash. */
978 x = (long)intpart;
979 if (x == -1)
980 x = -2;
981 return x;
982 }
983 /* The fractional part is non-zero, so we don't have to worry about
984 * making this match the hash of some other type.
985 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000986 * Since the VAX D double format has 56 mantissa bits, which is the
987 * most of any double format in use, each of these parts may have as
988 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000989 * So, assuming sizeof(long) >= 4, each part can be broken into two
990 * longs; frexp and multiplication are used to do that.
991 * Also, since the Cray double format has 15 exponent bits, which is
992 * the most of any double format in use, shifting the exponent field
993 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000994 */
Tim Peters39dce292000-08-15 03:34:48 +0000995 v = frexp(v, &expo);
996 v *= 2147483648.0; /* 2**31 */
997 hipart = (long)v; /* take the top 32 bits */
998 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
999 x = hipart + (long)v + (expo << 15);
1000 if (x == -1)
1001 x = -2;
1002 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001003}
1004
1005long
Fred Drake100814d2000-07-09 15:48:49 +00001006_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001007{
1008#if SIZEOF_LONG >= SIZEOF_VOID_P
1009 return (long)p;
1010#else
1011 /* convert to a Python long and hash that */
1012 PyObject* longobj;
1013 long x;
1014
1015 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1016 x = -1;
1017 goto finally;
1018 }
1019 x = PyObject_Hash(longobj);
1020
1021finally:
1022 Py_XDECREF(longobj);
1023 return x;
1024#endif
1025}
1026
1027
Guido van Rossum9bfef441993-03-29 10:43:31 +00001028long
Fred Drake100814d2000-07-09 15:48:49 +00001029PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001030{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001031 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001032 if (tp->tp_hash != NULL)
1033 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001034 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001035 return _Py_HashPointer(v); /* Use address as hash value */
1036 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001037 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001038 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001039 return -1;
1040}
1041
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001042PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001043PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001044{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001046
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001048 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049 w = PyString_InternFromString(name);
1050 if (w == NULL)
1051 return NULL;
1052 res = PyObject_GetAttr(v, w);
1053 Py_XDECREF(w);
1054 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001055}
1056
1057int
Fred Drake100814d2000-07-09 15:48:49 +00001058PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001059{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001060 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001061 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001062 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001063 return 1;
1064 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001065 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001066 return 0;
1067}
1068
1069int
Fred Drake100814d2000-07-09 15:48:49 +00001070PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001071{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072 PyObject *s;
1073 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001074
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001076 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077 s = PyString_InternFromString(name);
1078 if (s == NULL)
1079 return -1;
1080 res = PyObject_SetAttr(v, s, w);
1081 Py_XDECREF(s);
1082 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001083}
1084
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001085PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001086PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001087{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001088 PyTypeObject *tp = v->ob_type;
1089
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001090 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001091#ifdef Py_USING_UNICODE
1092 /* The Unicode to string conversion is done here because the
1093 existing tp_getattro slots expect a string object as name
1094 and we wouldn't want to break those. */
1095 if (PyUnicode_Check(name)) {
1096 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1097 if (name == NULL)
1098 return NULL;
1099 }
1100 else
1101#endif
1102 {
1103 PyErr_SetString(PyExc_TypeError,
1104 "attribute name must be string");
1105 return NULL;
1106 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108 if (tp->tp_getattro != NULL)
1109 return (*tp->tp_getattro)(v, name);
1110 if (tp->tp_getattr != NULL)
1111 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1112 PyErr_Format(PyExc_AttributeError,
1113 "'%.50s' object has no attribute '%.400s'",
1114 tp->tp_name, PyString_AS_STRING(name));
1115 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001116}
1117
1118int
Fred Drake100814d2000-07-09 15:48:49 +00001119PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001120{
1121 PyObject *res = PyObject_GetAttr(v, name);
1122 if (res != NULL) {
1123 Py_DECREF(res);
1124 return 1;
1125 }
1126 PyErr_Clear();
1127 return 0;
1128}
1129
1130int
Fred Drake100814d2000-07-09 15:48:49 +00001131PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001132{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001134 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001135
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001136 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001137#ifdef Py_USING_UNICODE
1138 /* The Unicode to string conversion is done here because the
1139 existing tp_setattro slots expect a string object as name
1140 and we wouldn't want to break those. */
1141 if (PyUnicode_Check(name)) {
1142 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1143 if (name == NULL)
1144 return -1;
1145 }
1146 else
1147#endif
1148 {
1149 PyErr_SetString(PyExc_TypeError,
1150 "attribute name must be string");
1151 return -1;
1152 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001153 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001154 else
1155 Py_INCREF(name);
1156
1157 PyString_InternInPlace(&name);
1158 if (tp->tp_setattro != NULL) {
1159 err = (*tp->tp_setattro)(v, name, value);
1160 Py_DECREF(name);
1161 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001162 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163 if (tp->tp_setattr != NULL) {
1164 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1165 Py_DECREF(name);
1166 return err;
1167 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001168 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1170 PyErr_Format(PyExc_TypeError,
1171 "'%.100s' object has no attributes "
1172 "(%s .%.100s)",
1173 tp->tp_name,
1174 value==NULL ? "del" : "assign to",
1175 PyString_AS_STRING(name));
1176 else
1177 PyErr_Format(PyExc_TypeError,
1178 "'%.100s' object has only read-only attributes "
1179 "(%s .%.100s)",
1180 tp->tp_name,
1181 value==NULL ? "del" : "assign to",
1182 PyString_AS_STRING(name));
1183 return -1;
1184}
1185
1186/* Helper to get a pointer to an object's __dict__ slot, if any */
1187
1188PyObject **
1189_PyObject_GetDictPtr(PyObject *obj)
1190{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191 long dictoffset;
1192 PyTypeObject *tp = obj->ob_type;
1193
1194 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1195 return NULL;
1196 dictoffset = tp->tp_dictoffset;
1197 if (dictoffset == 0)
1198 return NULL;
1199 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001200 int tsize;
1201 size_t size;
1202
1203 tsize = ((PyVarObject *)obj)->ob_size;
1204 if (tsize < 0)
1205 tsize = -tsize;
1206 size = _PyObject_VAR_SIZE(tp, tsize);
1207
Tim Peters6d483d32001-10-06 21:27:34 +00001208 dictoffset += (long)size;
1209 assert(dictoffset > 0);
1210 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211 }
1212 return (PyObject **) ((char *)obj + dictoffset);
1213}
1214
1215/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1216
1217PyObject *
1218PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1219{
1220 PyTypeObject *tp = obj->ob_type;
1221 PyObject *descr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001222 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 descrgetfunc f;
1224 PyObject **dictptr;
1225
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001226 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001227#ifdef Py_USING_UNICODE
1228 /* The Unicode to string conversion is done here because the
1229 existing tp_setattro slots expect a string object as name
1230 and we wouldn't want to break those. */
1231 if (PyUnicode_Check(name)) {
1232 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1233 if (name == NULL)
1234 return NULL;
1235 }
1236 else
1237#endif
1238 {
1239 PyErr_SetString(PyExc_TypeError,
1240 "attribute name must be string");
1241 return NULL;
1242 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001243 }
1244 else
1245 Py_INCREF(name);
1246
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001248 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001249 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250 }
1251
1252 descr = _PyType_Lookup(tp, name);
1253 f = NULL;
1254 if (descr != NULL) {
1255 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001256 if (f != NULL && PyDescr_IsData(descr)) {
1257 res = f(descr, obj, (PyObject *)obj->ob_type);
1258 goto done;
1259 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 }
1261
1262 dictptr = _PyObject_GetDictPtr(obj);
1263 if (dictptr != NULL) {
1264 PyObject *dict = *dictptr;
1265 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001266 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267 if (res != NULL) {
1268 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001269 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 }
1271 }
1272 }
1273
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001274 if (f != NULL) {
1275 res = f(descr, obj, (PyObject *)obj->ob_type);
1276 goto done;
1277 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278
1279 if (descr != NULL) {
1280 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001281 res = descr;
1282 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283 }
1284
1285 PyErr_Format(PyExc_AttributeError,
1286 "'%.50s' object has no attribute '%.400s'",
1287 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001288 done:
1289 Py_DECREF(name);
1290 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291}
1292
1293int
1294PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1295{
1296 PyTypeObject *tp = obj->ob_type;
1297 PyObject *descr;
1298 descrsetfunc f;
1299 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001300 int res = -1;
1301
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001302 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001303#ifdef Py_USING_UNICODE
1304 /* The Unicode to string conversion is done here because the
1305 existing tp_setattro slots expect a string object as name
1306 and we wouldn't want to break those. */
1307 if (PyUnicode_Check(name)) {
1308 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1309 if (name == NULL)
1310 return -1;
1311 }
1312 else
1313#endif
1314 {
1315 PyErr_SetString(PyExc_TypeError,
1316 "attribute name must be string");
1317 return -1;
1318 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001319 }
1320 else
1321 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322
1323 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001324 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001325 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 }
1327
1328 descr = _PyType_Lookup(tp, name);
1329 f = NULL;
1330 if (descr != NULL) {
1331 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001332 if (f != NULL && PyDescr_IsData(descr)) {
1333 res = f(descr, obj, value);
1334 goto done;
1335 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336 }
1337
1338 dictptr = _PyObject_GetDictPtr(obj);
1339 if (dictptr != NULL) {
1340 PyObject *dict = *dictptr;
1341 if (dict == NULL && value != NULL) {
1342 dict = PyDict_New();
1343 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001344 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345 *dictptr = dict;
1346 }
1347 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348 if (value == NULL)
1349 res = PyDict_DelItem(dict, name);
1350 else
1351 res = PyDict_SetItem(dict, name, value);
1352 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1353 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001354 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355 }
1356 }
1357
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001358 if (f != NULL) {
1359 res = f(descr, obj, value);
1360 goto done;
1361 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362
1363 if (descr == NULL) {
1364 PyErr_Format(PyExc_AttributeError,
1365 "'%.50s' object has no attribute '%.400s'",
1366 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001367 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368 }
1369
1370 PyErr_Format(PyExc_AttributeError,
1371 "'%.50s' object attribute '%.400s' is read-only",
1372 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001373 done:
1374 Py_DECREF(name);
1375 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001376}
1377
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001378/* Test a value used as condition, e.g., in a for or if statement.
1379 Return -1 if an error occurred */
1380
1381int
Fred Drake100814d2000-07-09 15:48:49 +00001382PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001383{
1384 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001385 if (v == Py_None)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001386 res = 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001387 else if (v->ob_type->tp_as_number != NULL &&
1388 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001389 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001390 else if (v->ob_type->tp_as_mapping != NULL &&
1391 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001392 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001393 else if (v->ob_type->tp_as_sequence != NULL &&
1394 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001395 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1396 else
1397 res = 1;
1398 if (res > 0)
1399 res = 1;
1400 return res;
1401}
1402
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001403/* equivalent of 'not v'
1404 Return -1 if an error occurred */
1405
1406int
Fred Drake100814d2000-07-09 15:48:49 +00001407PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001408{
1409 int res;
1410 res = PyObject_IsTrue(v);
1411 if (res < 0)
1412 return res;
1413 return res == 0;
1414}
1415
Guido van Rossum5524a591995-01-10 15:26:20 +00001416/* Coerce two numeric types to the "larger" one.
1417 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001418 Return value:
1419 -1 if an error occurred;
1420 0 if the coercion succeeded (and then the reference counts are increased);
1421 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001422*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001423int
Fred Drake100814d2000-07-09 15:48:49 +00001424PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001425{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001426 register PyObject *v = *pv;
1427 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001428 int res;
1429
Guido van Rossum517c7d42002-04-26 02:49:14 +00001430 /* Shortcut only for old-style types */
1431 if (v->ob_type == w->ob_type &&
1432 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1433 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001434 Py_INCREF(v);
1435 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001436 return 0;
1437 }
1438 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1439 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1440 if (res <= 0)
1441 return res;
1442 }
1443 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1444 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1445 if (res <= 0)
1446 return res;
1447 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001448 return 1;
1449}
1450
Guido van Rossume797ec12001-01-17 15:24:28 +00001451/* Coerce two numeric types to the "larger" one.
1452 Increment the reference count on each argument.
1453 Return -1 and raise an exception if no coercion is possible
1454 (and then no reference count is incremented).
1455*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001456int
Fred Drake100814d2000-07-09 15:48:49 +00001457PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001458{
1459 int err = PyNumber_CoerceEx(pv, pw);
1460 if (err <= 0)
1461 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001462 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001463 return -1;
1464}
1465
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001466
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001467/* Test whether an object can be called */
1468
1469int
Fred Drake100814d2000-07-09 15:48:49 +00001470PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001471{
1472 if (x == NULL)
1473 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001474 if (PyInstance_Check(x)) {
1475 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001476 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001477 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001478 return 0;
1479 }
1480 /* Could test recursively but don't, for fear of endless
1481 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001482 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001483 return 1;
1484 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001485 else {
1486 return x->ob_type->tp_call != NULL;
1487 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001488}
1489
Tim Peters7eea37e2001-09-04 22:08:56 +00001490/* Helper for PyObject_Dir.
1491 Merge the __dict__ of aclass into dict, and recursively also all
1492 the __dict__s of aclass's base classes. The order of merging isn't
1493 defined, as it's expected that only the final set of dict keys is
1494 interesting.
1495 Return 0 on success, -1 on error.
1496*/
1497
1498static int
1499merge_class_dict(PyObject* dict, PyObject* aclass)
1500{
1501 PyObject *classdict;
1502 PyObject *bases;
1503
1504 assert(PyDict_Check(dict));
1505 assert(aclass);
1506
1507 /* Merge in the type's dict (if any). */
1508 classdict = PyObject_GetAttrString(aclass, "__dict__");
1509 if (classdict == NULL)
1510 PyErr_Clear();
1511 else {
1512 int status = PyDict_Update(dict, classdict);
1513 Py_DECREF(classdict);
1514 if (status < 0)
1515 return -1;
1516 }
1517
1518 /* Recursively merge in the base types' (if any) dicts. */
1519 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001520 if (bases == NULL)
1521 PyErr_Clear();
1522 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001523 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001524 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001525 n = PySequence_Size(bases); /* This better be right */
1526 if (n < 0)
1527 PyErr_Clear();
1528 else {
1529 for (i = 0; i < n; i++) {
1530 PyObject *base = PySequence_GetItem(bases, i);
1531 if (base == NULL) {
1532 Py_DECREF(bases);
1533 return -1;
1534 }
1535 if (merge_class_dict(dict, base) < 0) {
1536 Py_DECREF(bases);
1537 return -1;
1538 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001539 }
1540 }
1541 Py_DECREF(bases);
1542 }
1543 return 0;
1544}
1545
Tim Peters305b5852001-09-17 02:38:46 +00001546/* Helper for PyObject_Dir.
1547 If obj has an attr named attrname that's a list, merge its string
1548 elements into keys of dict.
1549 Return 0 on success, -1 on error. Errors due to not finding the attr,
1550 or the attr not being a list, are suppressed.
1551*/
1552
1553static int
1554merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1555{
1556 PyObject *list;
1557 int result = 0;
1558
1559 assert(PyDict_Check(dict));
1560 assert(obj);
1561 assert(attrname);
1562
1563 list = PyObject_GetAttrString(obj, attrname);
1564 if (list == NULL)
1565 PyErr_Clear();
1566
1567 else if (PyList_Check(list)) {
1568 int i;
1569 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1570 PyObject *item = PyList_GET_ITEM(list, i);
1571 if (PyString_Check(item)) {
1572 result = PyDict_SetItem(dict, item, Py_None);
1573 if (result < 0)
1574 break;
1575 }
1576 }
1577 }
1578
1579 Py_XDECREF(list);
1580 return result;
1581}
1582
Tim Peters7eea37e2001-09-04 22:08:56 +00001583/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1584 docstring, which should be kept in synch with this implementation. */
1585
1586PyObject *
1587PyObject_Dir(PyObject *arg)
1588{
1589 /* Set exactly one of these non-NULL before the end. */
1590 PyObject *result = NULL; /* result list */
1591 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1592
1593 /* If NULL arg, return the locals. */
1594 if (arg == NULL) {
1595 PyObject *locals = PyEval_GetLocals();
1596 if (locals == NULL)
1597 goto error;
1598 result = PyDict_Keys(locals);
1599 if (result == NULL)
1600 goto error;
1601 }
1602
1603 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001604 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001605 masterdict = PyObject_GetAttrString(arg, "__dict__");
1606 if (masterdict == NULL)
1607 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001608 if (!PyDict_Check(masterdict)) {
1609 PyErr_SetString(PyExc_TypeError,
1610 "module.__dict__ is not a dictionary");
1611 goto error;
1612 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001613 }
1614
1615 /* Elif some form of type or class, grab its dict and its bases.
1616 We deliberately don't suck up its __class__, as methods belonging
1617 to the metaclass would probably be more confusing than helpful. */
1618 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1619 masterdict = PyDict_New();
1620 if (masterdict == NULL)
1621 goto error;
1622 if (merge_class_dict(masterdict, arg) < 0)
1623 goto error;
1624 }
1625
1626 /* Else look at its dict, and the attrs reachable from its class. */
1627 else {
1628 PyObject *itsclass;
1629 /* Create a dict to start with. CAUTION: Not everything
1630 responding to __dict__ returns a dict! */
1631 masterdict = PyObject_GetAttrString(arg, "__dict__");
1632 if (masterdict == NULL) {
1633 PyErr_Clear();
1634 masterdict = PyDict_New();
1635 }
1636 else if (!PyDict_Check(masterdict)) {
1637 Py_DECREF(masterdict);
1638 masterdict = PyDict_New();
1639 }
1640 else {
1641 /* The object may have returned a reference to its
1642 dict, so copy it to avoid mutating it. */
1643 PyObject *temp = PyDict_Copy(masterdict);
1644 Py_DECREF(masterdict);
1645 masterdict = temp;
1646 }
1647 if (masterdict == NULL)
1648 goto error;
1649
Tim Peters305b5852001-09-17 02:38:46 +00001650 /* Merge in __members__ and __methods__ (if any).
1651 XXX Would like this to go away someday; for now, it's
1652 XXX needed to get at im_self etc of method objects. */
1653 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1654 goto error;
1655 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1656 goto error;
1657
Tim Peters7eea37e2001-09-04 22:08:56 +00001658 /* Merge in attrs reachable from its class.
1659 CAUTION: Not all objects have a __class__ attr. */
1660 itsclass = PyObject_GetAttrString(arg, "__class__");
1661 if (itsclass == NULL)
1662 PyErr_Clear();
1663 else {
1664 int status = merge_class_dict(masterdict, itsclass);
1665 Py_DECREF(itsclass);
1666 if (status < 0)
1667 goto error;
1668 }
1669 }
1670
1671 assert((result == NULL) ^ (masterdict == NULL));
1672 if (masterdict != NULL) {
1673 /* The result comes from its keys. */
1674 assert(result == NULL);
1675 result = PyDict_Keys(masterdict);
1676 if (result == NULL)
1677 goto error;
1678 }
1679
1680 assert(result);
1681 if (PyList_Sort(result) != 0)
1682 goto error;
1683 else
1684 goto normal_return;
1685
1686 error:
1687 Py_XDECREF(result);
1688 result = NULL;
1689 /* fall through */
1690 normal_return:
1691 Py_XDECREF(masterdict);
1692 return result;
1693}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001694
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001695/*
1696NoObject is usable as a non-NULL undefined value, used by the macro None.
1697There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001698so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001699(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001700*/
1701
Guido van Rossum0c182a11992-03-27 17:26:13 +00001702/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001703static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001704none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001705{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001706 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001707}
1708
Barry Warsaw9bf16442001-01-23 16:24:35 +00001709/* ARGUSED */
1710static void
1711none_dealloc(PyObject* ignore)
1712{
1713 /* This should never get called, but we also don't want to SEGV if
1714 * we accidently decref None out of existance.
1715 */
1716 abort();
1717}
1718
1719
Guido van Rossumba21a492001-08-16 08:17:26 +00001720static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001721 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001722 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001723 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001724 0,
1725 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001726 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001727 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001728 0, /*tp_getattr*/
1729 0, /*tp_setattr*/
1730 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001731 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001732 0, /*tp_as_number*/
1733 0, /*tp_as_sequence*/
1734 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001735 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001736};
1737
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001738PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001739 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740};
1741
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001742/* NotImplemented is an object that can be used to signal that an
1743 operation is not implemented for the given type combination. */
1744
1745static PyObject *
1746NotImplemented_repr(PyObject *op)
1747{
1748 return PyString_FromString("NotImplemented");
1749}
1750
1751static PyTypeObject PyNotImplemented_Type = {
1752 PyObject_HEAD_INIT(&PyType_Type)
1753 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001754 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001755 0,
1756 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001757 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001758 0, /*tp_print*/
1759 0, /*tp_getattr*/
1760 0, /*tp_setattr*/
1761 0, /*tp_compare*/
1762 (reprfunc)NotImplemented_repr, /*tp_repr*/
1763 0, /*tp_as_number*/
1764 0, /*tp_as_sequence*/
1765 0, /*tp_as_mapping*/
1766 0, /*tp_hash */
1767};
1768
1769PyObject _Py_NotImplementedStruct = {
1770 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1771};
1772
Guido van Rossumba21a492001-08-16 08:17:26 +00001773void
1774_Py_ReadyTypes(void)
1775{
1776 if (PyType_Ready(&PyType_Type) < 0)
1777 Py_FatalError("Can't initialize 'type'");
1778
Guido van Rossum77f6a652002-04-03 22:41:51 +00001779 if (PyType_Ready(&PyBool_Type) < 0)
1780 Py_FatalError("Can't initialize 'bool'");
1781
Guido van Rossumcacfc072002-05-24 19:01:59 +00001782 if (PyType_Ready(&PyString_Type) < 0)
1783 Py_FatalError("Can't initialize 'str'");
1784
Guido van Rossumba21a492001-08-16 08:17:26 +00001785 if (PyType_Ready(&PyList_Type) < 0)
1786 Py_FatalError("Can't initialize 'list'");
1787
1788 if (PyType_Ready(&PyNone_Type) < 0)
1789 Py_FatalError("Can't initialize type(None)");
1790
1791 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1792 Py_FatalError("Can't initialize type(NotImplemented)");
1793}
1794
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001795
Guido van Rossum84a90321996-05-22 16:34:47 +00001796#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001798static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001799
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001800void
Fred Drake100814d2000-07-09 15:48:49 +00001801_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001802{
1803 refchain._ob_prev = refchain._ob_next = &refchain;
1804 _Py_RefTotal = 0;
1805}
1806
1807void
Fred Drake100814d2000-07-09 15:48:49 +00001808_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001809{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001810 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001811 op->ob_refcnt = 1;
1812 op->_ob_next = refchain._ob_next;
1813 op->_ob_prev = &refchain;
1814 refchain._ob_next->_ob_prev = op;
1815 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001816#ifdef COUNT_ALLOCS
1817 inc_count(op->ob_type);
1818#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819}
1820
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001821void
Fred Drake100814d2000-07-09 15:48:49 +00001822_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001823{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001824#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001825 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001826#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001827 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001828 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001829 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001830 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001831 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001832#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001833 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1834 if (p == op)
1835 break;
1836 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001837 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001838 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001839#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001840 op->_ob_next->_ob_prev = op->_ob_prev;
1841 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001842 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001843#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001844 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001845#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001846}
1847
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001848void
Fred Drake100814d2000-07-09 15:48:49 +00001849_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001850{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001851 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001853 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854}
1855
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001856void
Fred Drake100814d2000-07-09 15:48:49 +00001857_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001859 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001860 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001861 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1862 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001863 if (PyObject_Print(op, fp, 0) != 0)
1864 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001865 putc('\n', fp);
1866 }
1867}
1868
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001869PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001870_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001871{
1872 int i, n;
1873 PyObject *t = NULL;
1874 PyObject *res, *op;
1875
1876 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1877 return NULL;
1878 op = refchain._ob_next;
1879 res = PyList_New(0);
1880 if (res == NULL)
1881 return NULL;
1882 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1883 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001884 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001885 op = op->_ob_next;
1886 if (op == &refchain)
1887 return res;
1888 }
1889 if (PyList_Append(res, op) < 0) {
1890 Py_DECREF(res);
1891 return NULL;
1892 }
1893 op = op->_ob_next;
1894 }
1895 return res;
1896}
1897
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001898#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001899
1900
1901/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001902PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001903
1904
1905/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001906int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001907
1908
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001909/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001910
Thomas Wouters334fb892000-07-25 12:56:38 +00001911void *
Fred Drake100814d2000-07-09 15:48:49 +00001912PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001913{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001914 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001915}
1916
Thomas Wouters334fb892000-07-25 12:56:38 +00001917void *
1918PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001919{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001920 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001921}
1922
1923void
Thomas Wouters334fb892000-07-25 12:56:38 +00001924PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001925{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001926 PyMem_FREE(p);
1927}
1928
1929
Guido van Rossum86610361998-04-10 22:32:46 +00001930/* These methods are used to control infinite recursion in repr, str, print,
1931 etc. Container objects that may recursively contain themselves,
1932 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1933 Py_ReprLeave() to avoid infinite recursion.
1934
1935 Py_ReprEnter() returns 0 the first time it is called for a particular
1936 object and 1 every time thereafter. It returns -1 if an exception
1937 occurred. Py_ReprLeave() has no return value.
1938
1939 See dictobject.c and listobject.c for examples of use.
1940*/
1941
1942#define KEY "Py_Repr"
1943
1944int
Fred Drake100814d2000-07-09 15:48:49 +00001945Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001946{
1947 PyObject *dict;
1948 PyObject *list;
1949 int i;
1950
1951 dict = PyThreadState_GetDict();
1952 if (dict == NULL)
1953 return -1;
1954 list = PyDict_GetItemString(dict, KEY);
1955 if (list == NULL) {
1956 list = PyList_New(0);
1957 if (list == NULL)
1958 return -1;
1959 if (PyDict_SetItemString(dict, KEY, list) < 0)
1960 return -1;
1961 Py_DECREF(list);
1962 }
1963 i = PyList_GET_SIZE(list);
1964 while (--i >= 0) {
1965 if (PyList_GET_ITEM(list, i) == obj)
1966 return 1;
1967 }
1968 PyList_Append(list, obj);
1969 return 0;
1970}
1971
1972void
Fred Drake100814d2000-07-09 15:48:49 +00001973Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001974{
1975 PyObject *dict;
1976 PyObject *list;
1977 int i;
1978
1979 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001980 if (dict == NULL)
1981 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001982 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001983 if (list == NULL || !PyList_Check(list))
1984 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001985 i = PyList_GET_SIZE(list);
1986 /* Count backwards because we always expect obj to be list[-1] */
1987 while (--i >= 0) {
1988 if (PyList_GET_ITEM(list, i) == obj) {
1989 PyList_SetSlice(list, i, i + 1, NULL);
1990 break;
1991 }
1992 }
1993}
Guido van Rossumd724b232000-03-13 16:01:29 +00001994
1995/*
1996 trashcan
1997 CT 2k0130
1998 non-recursively destroy nested objects
1999
2000 CT 2k0223
2001 everything is now done in a macro.
2002
2003 CT 2k0305
2004 modified to use functions, after Tim Peter's suggestion.
2005
2006 CT 2k0309
2007 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00002008
2009 CT 2k0325
2010 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00002011
2012 CT 2k0422
2013 complete rewrite. We now build a chain via ob_type
2014 and save the limited number of types in ob_refcnt.
2015 This is perfect since we don't need any memory.
2016 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00002017*/
2018
Guido van Rossume92e6102000-04-24 15:40:53 +00002019#define Py_TRASHCAN_TUPLE 1
2020#define Py_TRASHCAN_LIST 2
2021#define Py_TRASHCAN_DICT 3
2022#define Py_TRASHCAN_FRAME 4
2023#define Py_TRASHCAN_TRACEBACK 5
2024/* extend here if other objects want protection */
2025
Guido van Rossumd724b232000-03-13 16:01:29 +00002026int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002027
Guido van Rossumd724b232000-03-13 16:01:29 +00002028PyObject * _PyTrash_delete_later = NULL;
2029
2030void
Fred Drake100814d2000-07-09 15:48:49 +00002031_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002032{
Neil Schemenauerf589c052002-03-29 03:05:54 +00002033#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002034 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00002035
Guido van Rossume92e6102000-04-24 15:40:53 +00002036 if (PyTuple_Check(op))
2037 typecode = Py_TRASHCAN_TUPLE;
2038 else if (PyList_Check(op))
2039 typecode = Py_TRASHCAN_LIST;
2040 else if (PyDict_Check(op))
2041 typecode = Py_TRASHCAN_DICT;
2042 else if (PyFrame_Check(op))
2043 typecode = Py_TRASHCAN_FRAME;
2044 else if (PyTraceBack_Check(op))
2045 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00002046 else /* We have a bug here -- those are the only types in GC */ {
2047 Py_FatalError("Type not supported in GC -- internal bug");
2048 return; /* pacify compiler -- execution never here */
2049 }
Guido van Rossume92e6102000-04-24 15:40:53 +00002050 op->ob_refcnt = typecode;
Guido van Rossume92e6102000-04-24 15:40:53 +00002051 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002052#else
2053 assert (_Py_AS_GC(op)->gc.gc_next == NULL);
2054 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2055#endif
Guido van Rossume92e6102000-04-24 15:40:53 +00002056 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002057}
2058
2059void
Fred Drake100814d2000-07-09 15:48:49 +00002060_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002061{
2062 while (_PyTrash_delete_later) {
2063 PyObject *shredder = _PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002064
2065#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002066 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
2067
2068 switch (shredder->ob_refcnt) {
2069 case Py_TRASHCAN_TUPLE:
2070 shredder->ob_type = &PyTuple_Type;
2071 break;
2072 case Py_TRASHCAN_LIST:
2073 shredder->ob_type = &PyList_Type;
2074 break;
2075 case Py_TRASHCAN_DICT:
2076 shredder->ob_type = &PyDict_Type;
2077 break;
2078 case Py_TRASHCAN_FRAME:
2079 shredder->ob_type = &PyFrame_Type;
2080 break;
2081 case Py_TRASHCAN_TRACEBACK:
2082 shredder->ob_type = &PyTraceBack_Type;
2083 break;
2084 }
Neil Schemenauerf589c052002-03-29 03:05:54 +00002085#else
2086 _PyTrash_delete_later =
2087 (PyObject*) _Py_AS_GC(shredder)->gc.gc_prev;
2088#endif
2089
Guido van Rossume92e6102000-04-24 15:40:53 +00002090 _Py_NewReference(shredder);
2091
Guido van Rossumd724b232000-03-13 16:01:29 +00002092 ++_PyTrash_delete_nesting;
2093 Py_DECREF(shredder);
2094 --_PyTrash_delete_nesting;
2095 }
2096}