blob: 609083875857b4e3d8fec3d7988bc456f1e7b2f9 [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 Rossumc0b618a1997-05-02 03:12:38 +00001430 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1431 Py_INCREF(v);
1432 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001433 return 0;
1434 }
1435 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1436 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1437 if (res <= 0)
1438 return res;
1439 }
1440 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1441 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1442 if (res <= 0)
1443 return res;
1444 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001445 return 1;
1446}
1447
Guido van Rossume797ec12001-01-17 15:24:28 +00001448/* Coerce two numeric types to the "larger" one.
1449 Increment the reference count on each argument.
1450 Return -1 and raise an exception if no coercion is possible
1451 (and then no reference count is incremented).
1452*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001453int
Fred Drake100814d2000-07-09 15:48:49 +00001454PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001455{
1456 int err = PyNumber_CoerceEx(pv, pw);
1457 if (err <= 0)
1458 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001459 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001460 return -1;
1461}
1462
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001463
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001464/* Test whether an object can be called */
1465
1466int
Fred Drake100814d2000-07-09 15:48:49 +00001467PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001468{
1469 if (x == NULL)
1470 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001471 if (PyInstance_Check(x)) {
1472 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001473 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001474 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001475 return 0;
1476 }
1477 /* Could test recursively but don't, for fear of endless
1478 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001479 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001480 return 1;
1481 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 else {
1483 return x->ob_type->tp_call != NULL;
1484 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001485}
1486
Tim Peters7eea37e2001-09-04 22:08:56 +00001487/* Helper for PyObject_Dir.
1488 Merge the __dict__ of aclass into dict, and recursively also all
1489 the __dict__s of aclass's base classes. The order of merging isn't
1490 defined, as it's expected that only the final set of dict keys is
1491 interesting.
1492 Return 0 on success, -1 on error.
1493*/
1494
1495static int
1496merge_class_dict(PyObject* dict, PyObject* aclass)
1497{
1498 PyObject *classdict;
1499 PyObject *bases;
1500
1501 assert(PyDict_Check(dict));
1502 assert(aclass);
1503
1504 /* Merge in the type's dict (if any). */
1505 classdict = PyObject_GetAttrString(aclass, "__dict__");
1506 if (classdict == NULL)
1507 PyErr_Clear();
1508 else {
1509 int status = PyDict_Update(dict, classdict);
1510 Py_DECREF(classdict);
1511 if (status < 0)
1512 return -1;
1513 }
1514
1515 /* Recursively merge in the base types' (if any) dicts. */
1516 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001517 if (bases == NULL)
1518 PyErr_Clear();
1519 else {
Tim Peters7eea37e2001-09-04 22:08:56 +00001520 int i, n;
1521 assert(PyTuple_Check(bases));
1522 n = PyTuple_GET_SIZE(bases);
1523 for (i = 0; i < n; i++) {
1524 PyObject *base = PyTuple_GET_ITEM(bases, i);
1525 if (merge_class_dict(dict, base) < 0) {
1526 Py_DECREF(bases);
1527 return -1;
1528 }
1529 }
1530 Py_DECREF(bases);
1531 }
1532 return 0;
1533}
1534
Tim Peters305b5852001-09-17 02:38:46 +00001535/* Helper for PyObject_Dir.
1536 If obj has an attr named attrname that's a list, merge its string
1537 elements into keys of dict.
1538 Return 0 on success, -1 on error. Errors due to not finding the attr,
1539 or the attr not being a list, are suppressed.
1540*/
1541
1542static int
1543merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1544{
1545 PyObject *list;
1546 int result = 0;
1547
1548 assert(PyDict_Check(dict));
1549 assert(obj);
1550 assert(attrname);
1551
1552 list = PyObject_GetAttrString(obj, attrname);
1553 if (list == NULL)
1554 PyErr_Clear();
1555
1556 else if (PyList_Check(list)) {
1557 int i;
1558 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1559 PyObject *item = PyList_GET_ITEM(list, i);
1560 if (PyString_Check(item)) {
1561 result = PyDict_SetItem(dict, item, Py_None);
1562 if (result < 0)
1563 break;
1564 }
1565 }
1566 }
1567
1568 Py_XDECREF(list);
1569 return result;
1570}
1571
Tim Peters7eea37e2001-09-04 22:08:56 +00001572/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1573 docstring, which should be kept in synch with this implementation. */
1574
1575PyObject *
1576PyObject_Dir(PyObject *arg)
1577{
1578 /* Set exactly one of these non-NULL before the end. */
1579 PyObject *result = NULL; /* result list */
1580 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1581
1582 /* If NULL arg, return the locals. */
1583 if (arg == NULL) {
1584 PyObject *locals = PyEval_GetLocals();
1585 if (locals == NULL)
1586 goto error;
1587 result = PyDict_Keys(locals);
1588 if (result == NULL)
1589 goto error;
1590 }
1591
1592 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001593 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001594 masterdict = PyObject_GetAttrString(arg, "__dict__");
1595 if (masterdict == NULL)
1596 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001597 if (!PyDict_Check(masterdict)) {
1598 PyErr_SetString(PyExc_TypeError,
1599 "module.__dict__ is not a dictionary");
1600 goto error;
1601 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001602 }
1603
1604 /* Elif some form of type or class, grab its dict and its bases.
1605 We deliberately don't suck up its __class__, as methods belonging
1606 to the metaclass would probably be more confusing than helpful. */
1607 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1608 masterdict = PyDict_New();
1609 if (masterdict == NULL)
1610 goto error;
1611 if (merge_class_dict(masterdict, arg) < 0)
1612 goto error;
1613 }
1614
1615 /* Else look at its dict, and the attrs reachable from its class. */
1616 else {
1617 PyObject *itsclass;
1618 /* Create a dict to start with. CAUTION: Not everything
1619 responding to __dict__ returns a dict! */
1620 masterdict = PyObject_GetAttrString(arg, "__dict__");
1621 if (masterdict == NULL) {
1622 PyErr_Clear();
1623 masterdict = PyDict_New();
1624 }
1625 else if (!PyDict_Check(masterdict)) {
1626 Py_DECREF(masterdict);
1627 masterdict = PyDict_New();
1628 }
1629 else {
1630 /* The object may have returned a reference to its
1631 dict, so copy it to avoid mutating it. */
1632 PyObject *temp = PyDict_Copy(masterdict);
1633 Py_DECREF(masterdict);
1634 masterdict = temp;
1635 }
1636 if (masterdict == NULL)
1637 goto error;
1638
Tim Peters305b5852001-09-17 02:38:46 +00001639 /* Merge in __members__ and __methods__ (if any).
1640 XXX Would like this to go away someday; for now, it's
1641 XXX needed to get at im_self etc of method objects. */
1642 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1643 goto error;
1644 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1645 goto error;
1646
Tim Peters7eea37e2001-09-04 22:08:56 +00001647 /* Merge in attrs reachable from its class.
1648 CAUTION: Not all objects have a __class__ attr. */
1649 itsclass = PyObject_GetAttrString(arg, "__class__");
1650 if (itsclass == NULL)
1651 PyErr_Clear();
1652 else {
1653 int status = merge_class_dict(masterdict, itsclass);
1654 Py_DECREF(itsclass);
1655 if (status < 0)
1656 goto error;
1657 }
1658 }
1659
1660 assert((result == NULL) ^ (masterdict == NULL));
1661 if (masterdict != NULL) {
1662 /* The result comes from its keys. */
1663 assert(result == NULL);
1664 result = PyDict_Keys(masterdict);
1665 if (result == NULL)
1666 goto error;
1667 }
1668
1669 assert(result);
1670 if (PyList_Sort(result) != 0)
1671 goto error;
1672 else
1673 goto normal_return;
1674
1675 error:
1676 Py_XDECREF(result);
1677 result = NULL;
1678 /* fall through */
1679 normal_return:
1680 Py_XDECREF(masterdict);
1681 return result;
1682}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001683
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001684/*
1685NoObject is usable as a non-NULL undefined value, used by the macro None.
1686There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001687so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001688(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001689*/
1690
Guido van Rossum0c182a11992-03-27 17:26:13 +00001691/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001692static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001693none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001694{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001695 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001696}
1697
Barry Warsaw9bf16442001-01-23 16:24:35 +00001698/* ARGUSED */
1699static void
1700none_dealloc(PyObject* ignore)
1701{
1702 /* This should never get called, but we also don't want to SEGV if
1703 * we accidently decref None out of existance.
1704 */
1705 abort();
1706}
1707
1708
Guido van Rossumba21a492001-08-16 08:17:26 +00001709static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001710 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001711 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001712 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001713 0,
1714 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001715 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001716 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001717 0, /*tp_getattr*/
1718 0, /*tp_setattr*/
1719 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001720 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001721 0, /*tp_as_number*/
1722 0, /*tp_as_sequence*/
1723 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001724 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001725};
1726
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001727PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001728 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001729};
1730
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001731/* NotImplemented is an object that can be used to signal that an
1732 operation is not implemented for the given type combination. */
1733
1734static PyObject *
1735NotImplemented_repr(PyObject *op)
1736{
1737 return PyString_FromString("NotImplemented");
1738}
1739
1740static PyTypeObject PyNotImplemented_Type = {
1741 PyObject_HEAD_INIT(&PyType_Type)
1742 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001743 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001744 0,
1745 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001746 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001747 0, /*tp_print*/
1748 0, /*tp_getattr*/
1749 0, /*tp_setattr*/
1750 0, /*tp_compare*/
1751 (reprfunc)NotImplemented_repr, /*tp_repr*/
1752 0, /*tp_as_number*/
1753 0, /*tp_as_sequence*/
1754 0, /*tp_as_mapping*/
1755 0, /*tp_hash */
1756};
1757
1758PyObject _Py_NotImplementedStruct = {
1759 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1760};
1761
Guido van Rossumba21a492001-08-16 08:17:26 +00001762void
1763_Py_ReadyTypes(void)
1764{
1765 if (PyType_Ready(&PyType_Type) < 0)
1766 Py_FatalError("Can't initialize 'type'");
1767
Guido van Rossum77f6a652002-04-03 22:41:51 +00001768 if (PyType_Ready(&PyBool_Type) < 0)
1769 Py_FatalError("Can't initialize 'bool'");
1770
Guido van Rossumba21a492001-08-16 08:17:26 +00001771 if (PyType_Ready(&PyList_Type) < 0)
1772 Py_FatalError("Can't initialize 'list'");
1773
1774 if (PyType_Ready(&PyNone_Type) < 0)
1775 Py_FatalError("Can't initialize type(None)");
1776
1777 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1778 Py_FatalError("Can't initialize type(NotImplemented)");
1779}
1780
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001781
Guido van Rossum84a90321996-05-22 16:34:47 +00001782#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001783
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001784static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001785
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001786void
Fred Drake100814d2000-07-09 15:48:49 +00001787_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001788{
1789 refchain._ob_prev = refchain._ob_next = &refchain;
1790 _Py_RefTotal = 0;
1791}
1792
1793void
Fred Drake100814d2000-07-09 15:48:49 +00001794_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001795{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001796 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001797 op->ob_refcnt = 1;
1798 op->_ob_next = refchain._ob_next;
1799 op->_ob_prev = &refchain;
1800 refchain._ob_next->_ob_prev = op;
1801 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001802#ifdef COUNT_ALLOCS
1803 inc_count(op->ob_type);
1804#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001805}
1806
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001807void
Fred Drake100814d2000-07-09 15:48:49 +00001808_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001809{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001810#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001811 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001812#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001813 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001814 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001815 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001816 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001817 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001818#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001819 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1820 if (p == op)
1821 break;
1822 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001823 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001825#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001826 op->_ob_next->_ob_prev = op->_ob_prev;
1827 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001828 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001829#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001830 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001831#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001832}
1833
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001834void
Fred Drake100814d2000-07-09 15:48:49 +00001835_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001836{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001837 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001838 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001839 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001840}
1841
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001842void
Fred Drake100814d2000-07-09 15:48:49 +00001843_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001845 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001846 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1848 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001849 if (PyObject_Print(op, fp, 0) != 0)
1850 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851 putc('\n', fp);
1852 }
1853}
1854
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001855PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001856_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001857{
1858 int i, n;
1859 PyObject *t = NULL;
1860 PyObject *res, *op;
1861
1862 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1863 return NULL;
1864 op = refchain._ob_next;
1865 res = PyList_New(0);
1866 if (res == NULL)
1867 return NULL;
1868 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1869 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001870 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001871 op = op->_ob_next;
1872 if (op == &refchain)
1873 return res;
1874 }
1875 if (PyList_Append(res, op) < 0) {
1876 Py_DECREF(res);
1877 return NULL;
1878 }
1879 op = op->_ob_next;
1880 }
1881 return res;
1882}
1883
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001884#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001885
1886
1887/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001888PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001889
1890
1891/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001892int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001893
1894
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001895/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001896
Thomas Wouters334fb892000-07-25 12:56:38 +00001897void *
Fred Drake100814d2000-07-09 15:48:49 +00001898PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001899{
1900#if _PyMem_EXTRA > 0
1901 if (nbytes == 0)
1902 nbytes = _PyMem_EXTRA;
1903#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001904 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001905}
1906
Thomas Wouters334fb892000-07-25 12:56:38 +00001907void *
1908PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001909{
Tim Petersa5d78cc2002-03-02 08:43:19 +00001910 /* See comment near MALLOC_ZERO_RETURNS_NULL in pyport.h. */
1911 return PyMem_REALLOC(p, nbytes ? nbytes : 1);
Guido van Rossume09fb551997-08-05 02:04:34 +00001912}
1913
1914void
Thomas Wouters334fb892000-07-25 12:56:38 +00001915PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001916{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001917 PyMem_FREE(p);
1918}
1919
1920
Guido van Rossum86610361998-04-10 22:32:46 +00001921/* These methods are used to control infinite recursion in repr, str, print,
1922 etc. Container objects that may recursively contain themselves,
1923 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1924 Py_ReprLeave() to avoid infinite recursion.
1925
1926 Py_ReprEnter() returns 0 the first time it is called for a particular
1927 object and 1 every time thereafter. It returns -1 if an exception
1928 occurred. Py_ReprLeave() has no return value.
1929
1930 See dictobject.c and listobject.c for examples of use.
1931*/
1932
1933#define KEY "Py_Repr"
1934
1935int
Fred Drake100814d2000-07-09 15:48:49 +00001936Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001937{
1938 PyObject *dict;
1939 PyObject *list;
1940 int i;
1941
1942 dict = PyThreadState_GetDict();
1943 if (dict == NULL)
1944 return -1;
1945 list = PyDict_GetItemString(dict, KEY);
1946 if (list == NULL) {
1947 list = PyList_New(0);
1948 if (list == NULL)
1949 return -1;
1950 if (PyDict_SetItemString(dict, KEY, list) < 0)
1951 return -1;
1952 Py_DECREF(list);
1953 }
1954 i = PyList_GET_SIZE(list);
1955 while (--i >= 0) {
1956 if (PyList_GET_ITEM(list, i) == obj)
1957 return 1;
1958 }
1959 PyList_Append(list, obj);
1960 return 0;
1961}
1962
1963void
Fred Drake100814d2000-07-09 15:48:49 +00001964Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001965{
1966 PyObject *dict;
1967 PyObject *list;
1968 int i;
1969
1970 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001971 if (dict == NULL)
1972 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001973 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001974 if (list == NULL || !PyList_Check(list))
1975 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001976 i = PyList_GET_SIZE(list);
1977 /* Count backwards because we always expect obj to be list[-1] */
1978 while (--i >= 0) {
1979 if (PyList_GET_ITEM(list, i) == obj) {
1980 PyList_SetSlice(list, i, i + 1, NULL);
1981 break;
1982 }
1983 }
1984}
Guido van Rossumd724b232000-03-13 16:01:29 +00001985
1986/*
1987 trashcan
1988 CT 2k0130
1989 non-recursively destroy nested objects
1990
1991 CT 2k0223
1992 everything is now done in a macro.
1993
1994 CT 2k0305
1995 modified to use functions, after Tim Peter's suggestion.
1996
1997 CT 2k0309
1998 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001999
2000 CT 2k0325
2001 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00002002
2003 CT 2k0422
2004 complete rewrite. We now build a chain via ob_type
2005 and save the limited number of types in ob_refcnt.
2006 This is perfect since we don't need any memory.
2007 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00002008*/
2009
Guido van Rossume92e6102000-04-24 15:40:53 +00002010#define Py_TRASHCAN_TUPLE 1
2011#define Py_TRASHCAN_LIST 2
2012#define Py_TRASHCAN_DICT 3
2013#define Py_TRASHCAN_FRAME 4
2014#define Py_TRASHCAN_TRACEBACK 5
2015/* extend here if other objects want protection */
2016
Guido van Rossumd724b232000-03-13 16:01:29 +00002017int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002018
Guido van Rossumd724b232000-03-13 16:01:29 +00002019PyObject * _PyTrash_delete_later = NULL;
2020
2021void
Fred Drake100814d2000-07-09 15:48:49 +00002022_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002023{
Neil Schemenauerf589c052002-03-29 03:05:54 +00002024#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002025 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00002026
Guido van Rossume92e6102000-04-24 15:40:53 +00002027 if (PyTuple_Check(op))
2028 typecode = Py_TRASHCAN_TUPLE;
2029 else if (PyList_Check(op))
2030 typecode = Py_TRASHCAN_LIST;
2031 else if (PyDict_Check(op))
2032 typecode = Py_TRASHCAN_DICT;
2033 else if (PyFrame_Check(op))
2034 typecode = Py_TRASHCAN_FRAME;
2035 else if (PyTraceBack_Check(op))
2036 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00002037 else /* We have a bug here -- those are the only types in GC */ {
2038 Py_FatalError("Type not supported in GC -- internal bug");
2039 return; /* pacify compiler -- execution never here */
2040 }
Guido van Rossume92e6102000-04-24 15:40:53 +00002041 op->ob_refcnt = typecode;
Guido van Rossume92e6102000-04-24 15:40:53 +00002042 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002043#else
2044 assert (_Py_AS_GC(op)->gc.gc_next == NULL);
2045 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2046#endif
Guido van Rossume92e6102000-04-24 15:40:53 +00002047 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002048}
2049
2050void
Fred Drake100814d2000-07-09 15:48:49 +00002051_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002052{
2053 while (_PyTrash_delete_later) {
2054 PyObject *shredder = _PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002055
2056#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002057 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
2058
2059 switch (shredder->ob_refcnt) {
2060 case Py_TRASHCAN_TUPLE:
2061 shredder->ob_type = &PyTuple_Type;
2062 break;
2063 case Py_TRASHCAN_LIST:
2064 shredder->ob_type = &PyList_Type;
2065 break;
2066 case Py_TRASHCAN_DICT:
2067 shredder->ob_type = &PyDict_Type;
2068 break;
2069 case Py_TRASHCAN_FRAME:
2070 shredder->ob_type = &PyFrame_Type;
2071 break;
2072 case Py_TRASHCAN_TRACEBACK:
2073 shredder->ob_type = &PyTraceBack_Type;
2074 break;
2075 }
Neil Schemenauerf589c052002-03-29 03:05:54 +00002076#else
2077 _PyTrash_delete_later =
2078 (PyObject*) _Py_AS_GC(shredder)->gc.gc_prev;
2079#endif
2080
Guido van Rossume92e6102000-04-24 15:40:53 +00002081 _Py_NewReference(shredder);
2082
Guido van Rossumd724b232000-03-13 16:01:29 +00002083 ++_PyTrash_delete_nesting;
2084 Py_DECREF(shredder);
2085 --_PyTrash_delete_nesting;
2086 }
2087}