blob: 7e4a211c0d84016688a6cf7cba0e746928f8dc95 [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 Rossum3f5da241990-12-20 15:06:42 +000019/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
20 These are used by the individual routines for object creation.
21 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000023#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000024static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000025extern int tuple_zero_allocs, fast_tuple_allocs;
26extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000027extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000028void
Fred Drake100814d2000-07-09 15:48:49 +000029dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000030{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000031 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000032
33 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000034 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000035 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000036 tp->tp_maxalloc);
37 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
38 fast_tuple_allocs, tuple_zero_allocs);
39 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
40 quick_int_allocs, quick_neg_int_allocs);
41 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
42 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000043}
44
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000045PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000046get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000047{
48 PyTypeObject *tp;
49 PyObject *result;
50 PyObject *v;
51
52 result = PyList_New(0);
53 if (result == NULL)
54 return NULL;
55 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000056 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
57 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000058 if (v == NULL) {
59 Py_DECREF(result);
60 return NULL;
61 }
62 if (PyList_Append(result, v) < 0) {
63 Py_DECREF(v);
64 Py_DECREF(result);
65 return NULL;
66 }
67 Py_DECREF(v);
68 }
69 return result;
70}
71
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000072void
Fred Drake100814d2000-07-09 15:48:49 +000073inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074{
Tim Peters6d6c1a32001-08-02 04:15:00 +000075 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +000076 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000077 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000078 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000079 tp->tp_next = type_list;
80 type_list = tp;
81 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000082 tp->tp_allocs++;
83 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
84 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000085}
86#endif
87
Guido van Rossumc0b618a1997-05-02 03:12:38 +000088PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000089PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090{
Guido van Rossumb18618d2000-05-03 23:44:39 +000091 if (op == NULL) {
92 PyErr_SetString(PyExc_SystemError,
93 "NULL object passed to PyObject_Init");
94 return op;
95 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000096 if (PyType_IS_GC(tp))
97 op = (PyObject *) PyObject_FROM_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +000098 /* 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 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000112 if (PyType_IS_GC(tp))
113 op = (PyVarObject *) PyObject_FROM_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000114 /* Any changes should be reflected in PyObject_INIT_VAR */
115 op->ob_size = size;
116 op->ob_type = tp;
117 _Py_NewReference((PyObject *)op);
118 return op;
119}
120
121PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000122_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000123{
124 PyObject *op;
125 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
126 if (op == NULL)
127 return PyErr_NoMemory();
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000128 if (PyType_IS_GC(tp))
129 op = (PyObject *) PyObject_FROM_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000130 return PyObject_INIT(op, tp);
131}
132
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000133PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000134_PyObject_NewVar(PyTypeObject *tp, int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000136 PyVarObject *op;
137 op = (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE(tp, size));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000139 return (PyVarObject *)PyErr_NoMemory();
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000140 if (PyType_IS_GC(tp))
141 op = (PyVarObject *) PyObject_FROM_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000142 return PyObject_INIT_VAR(op, tp, size);
143}
144
145void
Fred Drake100814d2000-07-09 15:48:49 +0000146_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000147{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000148 if (op && PyType_IS_GC(op->ob_type)) {
149 op = (PyObject *) PyObject_AS_GC(op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000150 }
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000151 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152}
153
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000154#ifndef WITH_CYCLE_GC
155/* extension modules might need these */
156void _PyGC_Insert(PyObject *op) { }
157void _PyGC_Remove(PyObject *op) { }
158#endif
159
Guido van Rossum90933611991-06-07 16:10:43 +0000160int
Fred Drake100814d2000-07-09 15:48:49 +0000161PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162{
Guido van Rossum278ef591991-07-27 21:40:24 +0000163 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000165 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000166#ifdef USE_STACKCHECK
167 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000168 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000169 return -1;
170 }
171#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000172 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000173 if (op == NULL) {
174 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175 }
Guido van Rossum90933611991-06-07 16:10:43 +0000176 else {
177 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000178 fprintf(fp, "<refcnt %u at %p>",
179 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000180 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000181 PyObject *s;
182 if (flags & Py_PRINT_RAW)
183 s = PyObject_Str(op);
184 else
185 s = PyObject_Repr(op);
186 if (s == NULL)
187 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000188 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000189 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000190 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000191 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000192 }
Guido van Rossum90933611991-06-07 16:10:43 +0000193 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000194 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000195 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000196 if (ret == 0) {
197 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000198 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000199 clearerr(fp);
200 ret = -1;
201 }
202 }
203 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204}
205
Barry Warsaw9bf16442001-01-23 16:24:35 +0000206/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Barry Warsawbbd89b62001-01-24 04:18:13 +0000207void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000208{
Barry Warsaweefb1072001-02-22 22:39:18 +0000209 if (op == NULL)
210 fprintf(stderr, "NULL\n");
211 else {
212 (void)PyObject_Print(op, stderr, 0);
213 fprintf(stderr, "\nrefcounts: %d\n", op->ob_refcnt);
214 fprintf(stderr, "address : %p\n", op);
215 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000216}
Barry Warsaw903138f2001-01-23 16:33:18 +0000217
218#ifdef WITH_CYCLE_GC
Barry Warsawbbd89b62001-01-24 04:18:13 +0000219void _PyGC_Dump(PyGC_Head* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000220{
Barry Warsawbbd89b62001-01-24 04:18:13 +0000221 _PyObject_Dump(PyObject_FROM_GC(op));
Barry Warsaw9bf16442001-01-23 16:24:35 +0000222}
Barry Warsaw903138f2001-01-23 16:33:18 +0000223#endif /* WITH_CYCLE_GC */
Barry Warsaw9bf16442001-01-23 16:24:35 +0000224
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000225PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000226PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000228 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000229 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000230#ifdef USE_STACKCHECK
231 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000232 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000233 return NULL;
234 }
235#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000236 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000237 return PyString_FromString("<NULL>");
Guido van Rossum90933611991-06-07 16:10:43 +0000238 else if (v->ob_type->tp_repr == NULL) {
239 char buf[120];
Fred Drakea44d3532000-06-30 15:01:00 +0000240 sprintf(buf, "<%.80s object at %p>",
241 v->ob_type->tp_name, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000244 else {
245 PyObject *res;
246 res = (*v->ob_type->tp_repr)(v);
247 if (res == NULL)
248 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000249#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000250 if (PyUnicode_Check(res)) {
251 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000252 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000253 Py_DECREF(res);
254 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000255 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000256 else
257 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000258 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000259#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000260 if (!PyString_Check(res)) {
261 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000262 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000263 res->ob_type->tp_name);
264 Py_DECREF(res);
265 return NULL;
266 }
267 return res;
268 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000269}
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000272PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000273{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000274 PyObject *res;
275
Guido van Rossumc6004111993-11-05 10:22:19 +0000276 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277 return PyString_FromString("<NULL>");
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000278 if (PyString_Check(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000280 return v;
281 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000282 if (v->ob_type->tp_str == NULL)
283 return PyObject_Repr(v);
284
285 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000286 if (res == NULL)
287 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000288#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000289 if (PyUnicode_Check(res)) {
290 PyObject* str;
291 str = PyUnicode_AsEncodedString(res, NULL, NULL);
292 Py_DECREF(res);
293 if (str)
294 res = str;
295 else
296 return NULL;
297 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000298#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000299 if (!PyString_Check(res)) {
300 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000301 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000302 res->ob_type->tp_name);
303 Py_DECREF(res);
304 return NULL;
305 }
306 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000307}
308
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000309#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000310PyObject *
311PyObject_Unicode(PyObject *v)
312{
313 PyObject *res;
314
315 if (v == NULL)
316 res = PyString_FromString("<NULL>");
317 else if (PyUnicode_Check(v)) {
318 Py_INCREF(v);
319 return v;
320 }
Marc-André Lemburgae605342001-03-25 19:16:13 +0000321 else if (PyString_Check(v)) {
322 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000323 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000324 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000325 else if (v->ob_type->tp_str != NULL)
326 res = (*v->ob_type->tp_str)(v);
327 else {
328 PyObject *func;
329 static PyObject *strstr;
330 if (strstr == NULL) {
331 strstr= PyString_InternFromString("__str__");
332 if (strstr == NULL)
333 return NULL;
334 }
335 if (!PyInstance_Check(v) ||
336 (func = PyObject_GetAttr(v, strstr)) == NULL) {
337 PyErr_Clear();
338 res = PyObject_Repr(v);
339 }
340 else {
341 res = PyEval_CallObject(func, (PyObject *)NULL);
342 Py_DECREF(func);
343 }
344 }
345 if (res == NULL)
346 return NULL;
347 if (!PyUnicode_Check(res)) {
348 PyObject* str;
349 str = PyUnicode_FromObject(res);
350 Py_DECREF(res);
351 if (str)
352 res = str;
353 else
354 return NULL;
355 }
356 return res;
357}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000358#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000359
360
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000361/* Macro to get the tp_richcompare field of a type if defined */
362#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
363 ? (t)->tp_richcompare : NULL)
364
Guido van Rossume797ec12001-01-17 15:24:28 +0000365/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
366static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000367
Guido van Rossume797ec12001-01-17 15:24:28 +0000368/* Try a genuine rich comparison, returning an object. Return:
369 NULL for exception;
370 NotImplemented if this particular rich comparison is not implemented or
371 undefined;
372 some object not equal to NotImplemented if it is implemented
373 (this latter object may not be a Boolean).
374*/
375static PyObject *
376try_rich_compare(PyObject *v, PyObject *w, int op)
377{
378 richcmpfunc f;
379 PyObject *res;
380
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000381 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000382 res = (*f)(v, w, op);
383 if (res != Py_NotImplemented)
384 return res;
385 Py_DECREF(res);
386 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000387 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000388 return (*f)(w, v, swapped_op[op]);
389 }
390 res = Py_NotImplemented;
391 Py_INCREF(res);
392 return res;
393}
394
395/* Try a genuine rich comparison, returning an int. Return:
396 -1 for exception (including the case where try_rich_compare() returns an
397 object that's not a Boolean);
398 0 if the outcome is false;
399 1 if the outcome is true;
400 2 if this particular rich comparison is not implemented or undefined.
401*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000402static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000403try_rich_compare_bool(PyObject *v, PyObject *w, int op)
404{
405 PyObject *res;
406 int ok;
407
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000408 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000409 return 2; /* Shortcut, avoid INCREF+DECREF */
410 res = try_rich_compare(v, w, op);
411 if (res == NULL)
412 return -1;
413 if (res == Py_NotImplemented) {
414 Py_DECREF(res);
415 return 2;
416 }
417 ok = PyObject_IsTrue(res);
418 Py_DECREF(res);
419 return ok;
420}
421
422/* Try rich comparisons to determine a 3-way comparison. Return:
423 -2 for an exception;
424 -1 if v < w;
425 0 if v == w;
426 1 if v > w;
427 2 if this particular rich comparison is not implemented or undefined.
428*/
429static int
430try_rich_to_3way_compare(PyObject *v, PyObject *w)
431{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000432 static struct { int op; int outcome; } tries[3] = {
433 /* Try this operator, and if it is true, use this outcome: */
434 {Py_EQ, 0},
435 {Py_LT, -1},
436 {Py_GT, 1},
437 };
438 int i;
439
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000440 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000441 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000442
443 for (i = 0; i < 3; i++) {
444 switch (try_rich_compare_bool(v, w, tries[i].op)) {
445 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000446 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000447 case 1:
448 return tries[i].outcome;
449 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000450 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000451
452 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000453}
454
455/* Try a 3-way comparison, returning an int. Return:
456 -2 for an exception;
457 -1 if v < w;
458 0 if v == w;
459 1 if v > w;
460 2 if this particular 3-way comparison is not implemented or undefined.
461*/
462static int
463try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000464{
465 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000466 cmpfunc f;
467
468 /* Comparisons involving instances are given to instance_compare,
469 which has the same return conventions as this function. */
470
471 if (PyInstance_Check(v))
472 return (*v->ob_type->tp_compare)(v, w);
473 if (PyInstance_Check(w))
474 return (*w->ob_type->tp_compare)(v, w);
475
Guido van Rossume797ec12001-01-17 15:24:28 +0000476 /* Try coercion; if it fails, give up */
477 c = PyNumber_CoerceEx(&v, &w);
478 if (c < 0)
479 return -2;
480 if (c > 0)
481 return 2;
482
483 /* Try v's comparison, if defined */
484 if ((f = v->ob_type->tp_compare) != NULL) {
485 c = (*f)(v, w);
486 Py_DECREF(v);
487 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000488 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000489 return -2;
490 return c < 0 ? -1 : c > 0 ? 1 : 0;
491 }
492
493 /* Try w's comparison, if defined */
494 if ((f = w->ob_type->tp_compare) != NULL) {
495 c = (*f)(w, v); /* swapped! */
496 Py_DECREF(v);
497 Py_DECREF(w);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000498 if (c < 0 && PyErr_Occurred())
Guido van Rossume797ec12001-01-17 15:24:28 +0000499 return -2;
500 return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
501 }
502
503 /* No comparison defined */
504 Py_DECREF(v);
505 Py_DECREF(w);
506 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000507}
508
Guido van Rossume797ec12001-01-17 15:24:28 +0000509/* Final fallback 3-way comparison, returning an int. Return:
510 -2 if an error occurred;
511 -1 if v < w;
512 0 if v == w;
513 1 if v > w.
514*/
515static int
516default_3way_compare(PyObject *v, PyObject *w)
517{
518 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000519 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000520
521 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000522 /* When comparing these pointers, they must be cast to
523 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
524 * uintptr_t). ANSI specifies that pointer compares other
525 * than == and != to non-related structures are undefined.
526 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000527 Py_uintptr_t vv = (Py_uintptr_t)v;
528 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000529 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
530 }
531
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000532#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000533 /* Special case for Unicode */
534 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
535 c = PyUnicode_Compare(v, w);
536 if (!PyErr_Occurred())
537 return c;
538 /* TypeErrors are ignored: if Unicode coercion fails due
539 to one of the arguments not having the right type, we
540 continue as defined by the coercion protocol (see
541 above). Luckily, decoding errors are reported as
542 ValueErrors and are not masked by this technique. */
543 if (!PyErr_ExceptionMatches(PyExc_TypeError))
544 return -2;
545 PyErr_Clear();
546 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000547#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000548
Guido van Rossum0871e932001-01-22 19:28:09 +0000549 /* None is smaller than anything */
550 if (v == Py_None)
551 return -1;
552 if (w == Py_None)
553 return 1;
554
Guido van Rossume797ec12001-01-17 15:24:28 +0000555 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000556 if (v->ob_type->tp_as_number)
557 vname = "";
558 else
559 vname = v->ob_type->tp_name;
560 if (w->ob_type->tp_as_number)
561 wname = "";
562 else
563 wname = w->ob_type->tp_name;
564 c = strcmp(vname, wname);
565 if (c < 0)
566 return -1;
567 if (c > 0)
568 return 1;
569 /* Same type name, or (more likely) incomparable numeric types */
570 return ((Py_uintptr_t)(v->ob_type) < (
571 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000572}
573
574#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
575
Tim Peters6d60b2e2001-05-07 20:53:51 +0000576/* Do a 3-way comparison, by hook or by crook. Return:
577 -2 for an exception;
578 -1 if v < w;
579 0 if v == w;
580 1 if v > w;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000581 If the object implements a tp_compare function, it returns
582 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000583*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000584static int
Fred Drake100814d2000-07-09 15:48:49 +0000585do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000586{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000587 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000588 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000589
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000590 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000591 && (f = v->ob_type->tp_compare) != NULL) {
592 c = (*f)(v, w);
593 if (c != 2 || !PyInstance_Check(v))
594 return c;
595 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000596 c = try_rich_to_3way_compare(v, w);
597 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000598 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000599 c = try_3way_compare(v, w);
600 if (c < 2)
601 return c;
602 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000603}
604
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000605/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000606 some types) and decremented on exit. If the count exceeds the
607 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000608
609 This is a tunable parameter that should only affect the performance
610 of comparisons, nothing else. Setting it high makes comparing deeply
611 nested non-cyclical data structures faster, but makes comparing cyclical
612 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000613*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000614#define NESTING_LIMIT 20
615
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000616static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000617
618static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000619get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000620{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000621 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000622 PyObject *tstate_dict, *inprogress;
623
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000624 if (key == NULL) {
625 key = PyString_InternFromString("cmp_state");
626 if (key == NULL)
627 return NULL;
628 }
629
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000630 tstate_dict = PyThreadState_GetDict();
631 if (tstate_dict == NULL) {
632 PyErr_BadInternalCall();
633 return NULL;
634 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000635
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000636 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000637 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000638 inprogress = PyDict_New();
639 if (inprogress == NULL)
640 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000641 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000642 Py_DECREF(inprogress);
643 return NULL;
644 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000645 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000646 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000647
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000648 return inprogress;
649}
650
651static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000652check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000653{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000654 PyObject *inprogress;
655 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000656 Py_uintptr_t iv = (Py_uintptr_t)v;
657 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000658 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000659
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000660 inprogress = get_inprogress_dict();
661 if (inprogress == NULL)
662 return NULL;
663
664 token = PyTuple_New(3);
665 if (token == NULL)
666 return NULL;
667
668 if (iv <= iw) {
669 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
670 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
671 if (op >= 0)
672 op = swapped_op[op];
673 } else {
674 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
675 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
676 }
677 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
678 if (x == NULL || y == NULL || z == NULL) {
679 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000680 return NULL;
681 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000682
683 if (PyDict_GetItem(inprogress, token) != NULL) {
684 Py_DECREF(token);
685 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000686 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000687
688 if (PyDict_SetItem(inprogress, token, token) < 0) {
689 Py_DECREF(token);
690 return NULL;
691 }
692
693 return token;
694}
695
696static void
697delete_token(PyObject *token)
698{
699 PyObject *inprogress;
700
701 if (token == NULL || token == Py_None)
702 return;
703 inprogress = get_inprogress_dict();
704 if (inprogress == NULL)
705 PyErr_Clear();
706 else
707 PyDict_DelItem(inprogress, token);
708 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000709}
710
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000711int
Fred Drake100814d2000-07-09 15:48:49 +0000712PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000713{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000714 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000715 int result;
716
Jack Jansend49cbe12000-08-22 21:52:51 +0000717#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000718 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000719 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
720 return -1;
721 }
722#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000723 if (v == NULL || w == NULL) {
724 PyErr_BadInternalCall();
725 return -1;
726 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727 if (v == w)
728 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000729 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000730 compare_nesting++;
731 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000732 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000733 || (vtp->tp_as_sequence
734 && !PyString_Check(v)
735 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000736 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000737 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000738
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000739 if (token == NULL) {
740 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000741 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000742 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000743 /* already comparing these objects. assume
744 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000745 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000746 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000747 else {
748 result = do_cmp(v, w);
749 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000750 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000751 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000752 else {
753 result = do_cmp(v, w);
754 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000755 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000756 return result < 0 ? -1 : result;
757}
758
759static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000760convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000761{
Guido van Rossume797ec12001-01-17 15:24:28 +0000762 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000763 switch (op) {
764 case Py_LT: c = c < 0; break;
765 case Py_LE: c = c <= 0; break;
766 case Py_EQ: c = c == 0; break;
767 case Py_NE: c = c != 0; break;
768 case Py_GT: c = c > 0; break;
769 case Py_GE: c = c >= 0; break;
770 }
771 result = c ? Py_True : Py_False;
772 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000773 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000775
776
777static PyObject *
778try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
779{
780 int c;
781
782 c = try_3way_compare(v, w);
783 if (c >= 2)
784 c = default_3way_compare(v, w);
785 if (c <= -2)
786 return NULL;
787 return convert_3way_to_object(op, c);
788}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000789
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000790static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000791do_richcmp(PyObject *v, PyObject *w, int op)
792{
793 PyObject *res;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000794 cmpfunc f;
795
796 /* If the types are equal, don't bother with coercions etc.
797 Instances are special-cased in try_3way_compare, since
798 a result of 2 does *not* mean one value being greater
799 than the other. */
800 if (v->ob_type == w->ob_type
801 && (f = v->ob_type->tp_compare) != NULL
802 && !PyInstance_Check(v)) {
803 int c;
804 richcmpfunc f1;
805 if ((f1 = RICHCOMPARE(v->ob_type)) != NULL) {
806 /* If the type has richcmp, try it first.
807 try_rich_compare would try it two-sided,
808 which is not needed since we've a single
809 type only. */
810 res = (*f1)(v, w, op);
811 if (res != Py_NotImplemented)
812 return res;
813 Py_DECREF(res);
814 }
815 c = (*f)(v, w);
816 if (c < 0 && PyErr_Occurred())
817 return NULL;
818 return convert_3way_to_object(op, c);
819 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000820
821 res = try_rich_compare(v, w, op);
822 if (res != Py_NotImplemented)
823 return res;
824 Py_DECREF(res);
825
826 return try_3way_to_rich_compare(v, w, op);
827}
828
829PyObject *
830PyObject_RichCompare(PyObject *v, PyObject *w, int op)
831{
832 PyObject *res;
833
834 assert(Py_LT <= op && op <= Py_GE);
835
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000836 compare_nesting++;
837 if (compare_nesting > NESTING_LIMIT &&
838 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000839 || (v->ob_type->tp_as_sequence
840 && !PyString_Check(v)
841 && !PyTuple_Check(v)))) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000842 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000843 PyObject *token = check_recursion(v, w, op);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000844
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000845 if (token == NULL) {
846 res = NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000847 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000848 else if (token == Py_None) {
849 /* already comparing these objects with this operator.
850 assume they're equal until shown otherwise */
851 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000852 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000853 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000854 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000855 else {
856 PyErr_SetString(PyExc_ValueError,
857 "can't order recursive values");
858 res = NULL;
859 }
860 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000861 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000862 else {
863 res = do_richcmp(v, w, op);
864 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000865 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000866 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000867 else {
868 res = do_richcmp(v, w, op);
869 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000870 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000871 return res;
872}
873
Tim Petersde9725f2001-05-05 10:06:17 +0000874/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000875int
876PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
877{
878 PyObject *res = PyObject_RichCompare(v, w, op);
879 int ok;
880
881 if (res == NULL)
882 return -1;
883 ok = PyObject_IsTrue(res);
884 Py_DECREF(res);
885 return ok;
886}
Fred Drake13634cf2000-06-29 19:17:04 +0000887
888/* Set of hash utility functions to help maintaining the invariant that
889 iff a==b then hash(a)==hash(b)
890
891 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
892*/
893
894long
Fred Drake100814d2000-07-09 15:48:49 +0000895_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000896{
Tim Peters39dce292000-08-15 03:34:48 +0000897 double intpart, fractpart;
898 int expo;
899 long hipart;
900 long x; /* the final hash value */
901 /* This is designed so that Python numbers of different types
902 * that compare equal hash to the same value; otherwise comparisons
903 * of mapping keys will turn out weird.
904 */
905
906#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
907{
908 extended e;
909 fractpart = modf(v, &e);
910 intpart = e;
911}
912#else
913 fractpart = modf(v, &intpart);
914#endif
915 if (fractpart == 0.0) {
916 /* This must return the same hash as an equal int or long. */
917 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
918 /* Convert to long and use its hash. */
919 PyObject *plong; /* converted to Python long */
920 if (Py_IS_INFINITY(intpart))
921 /* can't convert to long int -- arbitrary */
922 v = v < 0 ? -271828.0 : 314159.0;
923 plong = PyLong_FromDouble(v);
924 if (plong == NULL)
925 return -1;
926 x = PyObject_Hash(plong);
927 Py_DECREF(plong);
928 return x;
929 }
930 /* Fits in a C long == a Python int, so is its own hash. */
931 x = (long)intpart;
932 if (x == -1)
933 x = -2;
934 return x;
935 }
936 /* The fractional part is non-zero, so we don't have to worry about
937 * making this match the hash of some other type.
938 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000939 * Since the VAX D double format has 56 mantissa bits, which is the
940 * most of any double format in use, each of these parts may have as
941 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000942 * So, assuming sizeof(long) >= 4, each part can be broken into two
943 * longs; frexp and multiplication are used to do that.
944 * Also, since the Cray double format has 15 exponent bits, which is
945 * the most of any double format in use, shifting the exponent field
946 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000947 */
Tim Peters39dce292000-08-15 03:34:48 +0000948 v = frexp(v, &expo);
949 v *= 2147483648.0; /* 2**31 */
950 hipart = (long)v; /* take the top 32 bits */
951 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
952 x = hipart + (long)v + (expo << 15);
953 if (x == -1)
954 x = -2;
955 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000956}
957
958long
Fred Drake100814d2000-07-09 15:48:49 +0000959_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000960{
961#if SIZEOF_LONG >= SIZEOF_VOID_P
962 return (long)p;
963#else
964 /* convert to a Python long and hash that */
965 PyObject* longobj;
966 long x;
967
968 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
969 x = -1;
970 goto finally;
971 }
972 x = PyObject_Hash(longobj);
973
974finally:
975 Py_XDECREF(longobj);
976 return x;
977#endif
978}
979
980
Guido van Rossum9bfef441993-03-29 10:43:31 +0000981long
Fred Drake100814d2000-07-09 15:48:49 +0000982PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000983{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000985 if (tp->tp_hash != NULL)
986 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000987 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000988 return _Py_HashPointer(v); /* Use address as hash value */
989 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000990 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000991 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000992 return -1;
993}
994
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000995PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000996PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000997{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000999
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001001 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002 w = PyString_InternFromString(name);
1003 if (w == NULL)
1004 return NULL;
1005 res = PyObject_GetAttr(v, w);
1006 Py_XDECREF(w);
1007 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001008}
1009
1010int
Fred Drake100814d2000-07-09 15:48:49 +00001011PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001012{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001013 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001014 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001015 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001016 return 1;
1017 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001018 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001019 return 0;
1020}
1021
1022int
Fred Drake100814d2000-07-09 15:48:49 +00001023PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001024{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025 PyObject *s;
1026 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001027
Tim Peters6d6c1a32001-08-02 04:15:00 +00001028 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001029 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030 s = PyString_InternFromString(name);
1031 if (s == NULL)
1032 return -1;
1033 res = PyObject_SetAttr(v, s, w);
1034 Py_XDECREF(s);
1035 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001036}
1037
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001038PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001039PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001040{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041 PyTypeObject *tp = v->ob_type;
1042
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001043#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001044 /* The Unicode to string conversion is done here because the
1045 existing tp_getattro slots expect a string object as name
1046 and we wouldn't want to break those. */
1047 if (PyUnicode_Check(name)) {
1048 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1049 if (name == NULL)
1050 return NULL;
1051 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001052#endif
1053
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001054 if (!PyString_Check(name)) {
1055 PyErr_SetString(PyExc_TypeError,
1056 "attribute name must be string");
1057 return NULL;
1058 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001059 if (tp->tp_getattro != NULL)
1060 return (*tp->tp_getattro)(v, name);
1061 if (tp->tp_getattr != NULL)
1062 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1063 PyErr_Format(PyExc_AttributeError,
1064 "'%.50s' object has no attribute '%.400s'",
1065 tp->tp_name, PyString_AS_STRING(name));
1066 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001067}
1068
1069int
Fred Drake100814d2000-07-09 15:48:49 +00001070PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001071{
1072 PyObject *res = PyObject_GetAttr(v, name);
1073 if (res != NULL) {
1074 Py_DECREF(res);
1075 return 1;
1076 }
1077 PyErr_Clear();
1078 return 0;
1079}
1080
1081int
Fred Drake100814d2000-07-09 15:48:49 +00001082PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001083{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001085 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001086
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001087#ifdef Py_USING_UNICODE
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001088 /* The Unicode to string conversion is done here because the
1089 existing tp_setattro slots expect a string object as name
1090 and we wouldn't want to break those. */
1091 if (PyUnicode_Check(name)) {
1092 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1093 if (name == NULL)
1094 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001095 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001096 else
1097#endif
1098 if (!PyString_Check(name)){
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001099 PyErr_SetString(PyExc_TypeError,
1100 "attribute name must be string");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001102 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001103 else
1104 Py_INCREF(name);
1105
1106 PyString_InternInPlace(&name);
1107 if (tp->tp_setattro != NULL) {
1108 err = (*tp->tp_setattro)(v, name, value);
1109 Py_DECREF(name);
1110 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 if (tp->tp_setattr != NULL) {
1113 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1114 Py_DECREF(name);
1115 return err;
1116 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001117 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1119 PyErr_Format(PyExc_TypeError,
1120 "'%.100s' object has no attributes "
1121 "(%s .%.100s)",
1122 tp->tp_name,
1123 value==NULL ? "del" : "assign to",
1124 PyString_AS_STRING(name));
1125 else
1126 PyErr_Format(PyExc_TypeError,
1127 "'%.100s' object has only read-only attributes "
1128 "(%s .%.100s)",
1129 tp->tp_name,
1130 value==NULL ? "del" : "assign to",
1131 PyString_AS_STRING(name));
1132 return -1;
1133}
1134
1135/* Helper to get a pointer to an object's __dict__ slot, if any */
1136
1137PyObject **
1138_PyObject_GetDictPtr(PyObject *obj)
1139{
1140#define PTRSIZE (sizeof(PyObject *))
1141
1142 long dictoffset;
1143 PyTypeObject *tp = obj->ob_type;
1144
1145 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1146 return NULL;
1147 dictoffset = tp->tp_dictoffset;
1148 if (dictoffset == 0)
1149 return NULL;
1150 if (dictoffset < 0) {
1151 dictoffset += PyType_BASICSIZE(tp);
1152 assert(dictoffset > 0); /* Sanity check */
1153 if (tp->tp_itemsize > 0) {
1154 int n = ((PyVarObject *)obj)->ob_size;
1155 if (n > 0) {
1156 dictoffset += tp->tp_itemsize * n;
1157 /* Round up, if necessary */
1158 if (tp->tp_itemsize % PTRSIZE != 0) {
1159 dictoffset += PTRSIZE - 1;
1160 dictoffset /= PTRSIZE;
1161 dictoffset *= PTRSIZE;
1162 }
1163 }
1164 }
1165 }
1166 return (PyObject **) ((char *)obj + dictoffset);
1167}
1168
1169/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1170
1171PyObject *
1172PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1173{
1174 PyTypeObject *tp = obj->ob_type;
1175 PyObject *descr;
1176 descrgetfunc f;
1177 PyObject **dictptr;
1178
1179 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001180 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001181 return NULL;
1182 }
1183
1184 descr = _PyType_Lookup(tp, name);
1185 f = NULL;
1186 if (descr != NULL) {
1187 f = descr->ob_type->tp_descr_get;
1188 if (f != NULL && PyDescr_IsData(descr))
1189 return f(descr, obj, (PyObject *)obj->ob_type);
1190 }
1191
1192 dictptr = _PyObject_GetDictPtr(obj);
1193 if (dictptr != NULL) {
1194 PyObject *dict = *dictptr;
1195 if (dict != NULL) {
1196 PyObject *res = PyDict_GetItem(dict, name);
1197 if (res != NULL) {
1198 Py_INCREF(res);
1199 return res;
1200 }
1201 }
1202 }
1203
1204 if (f != NULL)
1205 return f(descr, obj, (PyObject *)obj->ob_type);
1206
1207 if (descr != NULL) {
1208 Py_INCREF(descr);
1209 return descr;
1210 }
1211
1212 PyErr_Format(PyExc_AttributeError,
1213 "'%.50s' object has no attribute '%.400s'",
1214 tp->tp_name, PyString_AS_STRING(name));
1215 return NULL;
1216}
1217
1218int
1219PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1220{
1221 PyTypeObject *tp = obj->ob_type;
1222 PyObject *descr;
1223 descrsetfunc f;
1224 PyObject **dictptr;
1225
1226 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001227 if (PyType_Ready(tp) < 0)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 return -1;
1229 }
1230
1231 descr = _PyType_Lookup(tp, name);
1232 f = NULL;
1233 if (descr != NULL) {
1234 f = descr->ob_type->tp_descr_set;
1235 if (f != NULL && PyDescr_IsData(descr))
1236 return f(descr, obj, value);
1237 }
1238
1239 dictptr = _PyObject_GetDictPtr(obj);
1240 if (dictptr != NULL) {
1241 PyObject *dict = *dictptr;
1242 if (dict == NULL && value != NULL) {
1243 dict = PyDict_New();
1244 if (dict == NULL)
1245 return -1;
1246 *dictptr = dict;
1247 }
1248 if (dict != NULL) {
1249 int res;
1250 if (value == NULL)
1251 res = PyDict_DelItem(dict, name);
1252 else
1253 res = PyDict_SetItem(dict, name, value);
1254 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1255 PyErr_SetObject(PyExc_AttributeError, name);
1256 return res;
1257 }
1258 }
1259
1260 if (f != NULL)
1261 return f(descr, obj, value);
1262
1263 if (descr == NULL) {
1264 PyErr_Format(PyExc_AttributeError,
1265 "'%.50s' object has no attribute '%.400s'",
1266 tp->tp_name, PyString_AS_STRING(name));
1267 return -1;
1268 }
1269
1270 PyErr_Format(PyExc_AttributeError,
1271 "'%.50s' object attribute '%.400s' is read-only",
1272 tp->tp_name, PyString_AS_STRING(name));
1273 return -1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001274}
1275
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001276/* Test a value used as condition, e.g., in a for or if statement.
1277 Return -1 if an error occurred */
1278
1279int
Fred Drake100814d2000-07-09 15:48:49 +00001280PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001281{
1282 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001283 if (v == Py_None)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001284 res = 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001285 else if (v->ob_type->tp_as_number != NULL &&
1286 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001287 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001288 else if (v->ob_type->tp_as_mapping != NULL &&
1289 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001290 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001291 else if (v->ob_type->tp_as_sequence != NULL &&
1292 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001293 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1294 else
1295 res = 1;
1296 if (res > 0)
1297 res = 1;
1298 return res;
1299}
1300
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001301/* equivalent of 'not v'
1302 Return -1 if an error occurred */
1303
1304int
Fred Drake100814d2000-07-09 15:48:49 +00001305PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001306{
1307 int res;
1308 res = PyObject_IsTrue(v);
1309 if (res < 0)
1310 return res;
1311 return res == 0;
1312}
1313
Guido van Rossum5524a591995-01-10 15:26:20 +00001314/* Coerce two numeric types to the "larger" one.
1315 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001316 Return value:
1317 -1 if an error occurred;
1318 0 if the coercion succeeded (and then the reference counts are increased);
1319 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001320*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001321int
Fred Drake100814d2000-07-09 15:48:49 +00001322PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001323{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001324 register PyObject *v = *pv;
1325 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001326 int res;
1327
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001328 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1329 Py_INCREF(v);
1330 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001331 return 0;
1332 }
1333 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1334 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1335 if (res <= 0)
1336 return res;
1337 }
1338 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1339 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1340 if (res <= 0)
1341 return res;
1342 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001343 return 1;
1344}
1345
Guido van Rossume797ec12001-01-17 15:24:28 +00001346/* Coerce two numeric types to the "larger" one.
1347 Increment the reference count on each argument.
1348 Return -1 and raise an exception if no coercion is possible
1349 (and then no reference count is incremented).
1350*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001351int
Fred Drake100814d2000-07-09 15:48:49 +00001352PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001353{
1354 int err = PyNumber_CoerceEx(pv, pw);
1355 if (err <= 0)
1356 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001358 return -1;
1359}
1360
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001361
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001362/* Test whether an object can be called */
1363
1364int
Fred Drake100814d2000-07-09 15:48:49 +00001365PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001366{
1367 if (x == NULL)
1368 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001369 if (PyInstance_Check(x)) {
1370 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001371 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001373 return 0;
1374 }
1375 /* Could test recursively but don't, for fear of endless
1376 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001377 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001378 return 1;
1379 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 else {
1381 return x->ob_type->tp_call != NULL;
1382 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001383}
1384
1385
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001386/*
1387NoObject is usable as a non-NULL undefined value, used by the macro None.
1388There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001389so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001390(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001391*/
1392
Guido van Rossum0c182a11992-03-27 17:26:13 +00001393/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001394static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001395none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001396{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001397 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001398}
1399
Barry Warsaw9bf16442001-01-23 16:24:35 +00001400/* ARGUSED */
1401static void
1402none_dealloc(PyObject* ignore)
1403{
1404 /* This should never get called, but we also don't want to SEGV if
1405 * we accidently decref None out of existance.
1406 */
1407 abort();
1408}
1409
1410
Guido van Rossumba21a492001-08-16 08:17:26 +00001411static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001412 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001413 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001414 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001415 0,
1416 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001417 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001418 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001419 0, /*tp_getattr*/
1420 0, /*tp_setattr*/
1421 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001422 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001423 0, /*tp_as_number*/
1424 0, /*tp_as_sequence*/
1425 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001426 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001427};
1428
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001430 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001431};
1432
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001433/* NotImplemented is an object that can be used to signal that an
1434 operation is not implemented for the given type combination. */
1435
1436static PyObject *
1437NotImplemented_repr(PyObject *op)
1438{
1439 return PyString_FromString("NotImplemented");
1440}
1441
1442static PyTypeObject PyNotImplemented_Type = {
1443 PyObject_HEAD_INIT(&PyType_Type)
1444 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001445 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001446 0,
1447 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001448 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001449 0, /*tp_print*/
1450 0, /*tp_getattr*/
1451 0, /*tp_setattr*/
1452 0, /*tp_compare*/
1453 (reprfunc)NotImplemented_repr, /*tp_repr*/
1454 0, /*tp_as_number*/
1455 0, /*tp_as_sequence*/
1456 0, /*tp_as_mapping*/
1457 0, /*tp_hash */
1458};
1459
1460PyObject _Py_NotImplementedStruct = {
1461 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1462};
1463
Guido van Rossumba21a492001-08-16 08:17:26 +00001464void
1465_Py_ReadyTypes(void)
1466{
1467 if (PyType_Ready(&PyType_Type) < 0)
1468 Py_FatalError("Can't initialize 'type'");
1469
1470 if (PyType_Ready(&PyList_Type) < 0)
1471 Py_FatalError("Can't initialize 'list'");
1472
1473 if (PyType_Ready(&PyNone_Type) < 0)
1474 Py_FatalError("Can't initialize type(None)");
1475
1476 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1477 Py_FatalError("Can't initialize type(NotImplemented)");
1478}
1479
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001480
Guido van Rossum84a90321996-05-22 16:34:47 +00001481#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001482
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001483static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001484
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001485void
Fred Drake100814d2000-07-09 15:48:49 +00001486_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001487{
1488 refchain._ob_prev = refchain._ob_next = &refchain;
1489 _Py_RefTotal = 0;
1490}
1491
1492void
Fred Drake100814d2000-07-09 15:48:49 +00001493_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001494{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001495 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001496 op->ob_refcnt = 1;
1497 op->_ob_next = refchain._ob_next;
1498 op->_ob_prev = &refchain;
1499 refchain._ob_next->_ob_prev = op;
1500 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001501#ifdef COUNT_ALLOCS
1502 inc_count(op->ob_type);
1503#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001504}
1505
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001506void
Fred Drake100814d2000-07-09 15:48:49 +00001507_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001508{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001509#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001510 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001511#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001512 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001513 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001514 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001515 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001516 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001517#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001518 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1519 if (p == op)
1520 break;
1521 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001522 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001523 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001524#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001525 op->_ob_next->_ob_prev = op->_ob_prev;
1526 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001527 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001528#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001530#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001531}
1532
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001533void
Fred Drake100814d2000-07-09 15:48:49 +00001534_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001535{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001536 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001537 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001538 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001539}
1540
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001541void
Fred Drake100814d2000-07-09 15:48:49 +00001542_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001543{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001544 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001545 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001546 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1547 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001548 if (PyObject_Print(op, fp, 0) != 0)
1549 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001550 putc('\n', fp);
1551 }
1552}
1553
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001554PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001555_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001556{
1557 int i, n;
1558 PyObject *t = NULL;
1559 PyObject *res, *op;
1560
1561 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1562 return NULL;
1563 op = refchain._ob_next;
1564 res = PyList_New(0);
1565 if (res == NULL)
1566 return NULL;
1567 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1568 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001569 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001570 op = op->_ob_next;
1571 if (op == &refchain)
1572 return res;
1573 }
1574 if (PyList_Append(res, op) < 0) {
1575 Py_DECREF(res);
1576 return NULL;
1577 }
1578 op = op->_ob_next;
1579 }
1580 return res;
1581}
1582
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001583#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001584
1585
1586/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001587PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001588
1589
1590/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001591int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001592
1593
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001594/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001595
Thomas Wouters334fb892000-07-25 12:56:38 +00001596void *
Fred Drake100814d2000-07-09 15:48:49 +00001597PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001598{
1599#if _PyMem_EXTRA > 0
1600 if (nbytes == 0)
1601 nbytes = _PyMem_EXTRA;
1602#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001603 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001604}
1605
Thomas Wouters334fb892000-07-25 12:56:38 +00001606void *
1607PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001608{
1609#if _PyMem_EXTRA > 0
1610 if (nbytes == 0)
1611 nbytes = _PyMem_EXTRA;
1612#endif
Guido van Rossumb18618d2000-05-03 23:44:39 +00001613 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001614}
1615
1616void
Thomas Wouters334fb892000-07-25 12:56:38 +00001617PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001618{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001619 PyMem_FREE(p);
1620}
1621
1622
1623/* Python's object malloc wrappers (see objimpl.h) */
1624
Thomas Wouters334fb892000-07-25 12:56:38 +00001625void *
Fred Drake100814d2000-07-09 15:48:49 +00001626PyObject_Malloc(size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001627{
1628 return PyObject_MALLOC(nbytes);
1629}
1630
Thomas Wouters334fb892000-07-25 12:56:38 +00001631void *
1632PyObject_Realloc(void *p, size_t nbytes)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001633{
1634 return PyObject_REALLOC(p, nbytes);
1635}
1636
1637void
Thomas Wouters334fb892000-07-25 12:56:38 +00001638PyObject_Free(void *p)
Guido van Rossumb18618d2000-05-03 23:44:39 +00001639{
1640 PyObject_FREE(p);
Guido van Rossume09fb551997-08-05 02:04:34 +00001641}
Guido van Rossum86610361998-04-10 22:32:46 +00001642
1643
Fred Drake41deb1e2001-02-01 05:27:45 +00001644/* Hook to clear up weak references only once the _weakref module is
1645 imported. We use a dummy implementation to simplify the code at each
1646 call site instead of requiring a test for NULL.
1647*/
1648
Fred Drakeb60654b2001-02-26 18:56:37 +00001649static void
Fred Drake41deb1e2001-02-01 05:27:45 +00001650empty_clear_weak_refs(PyObject *o)
1651{
Fred Drakeb60654b2001-02-26 18:56:37 +00001652 return;
Fred Drake41deb1e2001-02-01 05:27:45 +00001653}
1654
Fred Drakeb60654b2001-02-26 18:56:37 +00001655void (*PyObject_ClearWeakRefs)(PyObject *) = empty_clear_weak_refs;
Fred Drake41deb1e2001-02-01 05:27:45 +00001656
1657
1658
Guido van Rossum86610361998-04-10 22:32:46 +00001659/* These methods are used to control infinite recursion in repr, str, print,
1660 etc. Container objects that may recursively contain themselves,
1661 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1662 Py_ReprLeave() to avoid infinite recursion.
1663
1664 Py_ReprEnter() returns 0 the first time it is called for a particular
1665 object and 1 every time thereafter. It returns -1 if an exception
1666 occurred. Py_ReprLeave() has no return value.
1667
1668 See dictobject.c and listobject.c for examples of use.
1669*/
1670
1671#define KEY "Py_Repr"
1672
1673int
Fred Drake100814d2000-07-09 15:48:49 +00001674Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001675{
1676 PyObject *dict;
1677 PyObject *list;
1678 int i;
1679
1680 dict = PyThreadState_GetDict();
1681 if (dict == NULL)
1682 return -1;
1683 list = PyDict_GetItemString(dict, KEY);
1684 if (list == NULL) {
1685 list = PyList_New(0);
1686 if (list == NULL)
1687 return -1;
1688 if (PyDict_SetItemString(dict, KEY, list) < 0)
1689 return -1;
1690 Py_DECREF(list);
1691 }
1692 i = PyList_GET_SIZE(list);
1693 while (--i >= 0) {
1694 if (PyList_GET_ITEM(list, i) == obj)
1695 return 1;
1696 }
1697 PyList_Append(list, obj);
1698 return 0;
1699}
1700
1701void
Fred Drake100814d2000-07-09 15:48:49 +00001702Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001703{
1704 PyObject *dict;
1705 PyObject *list;
1706 int i;
1707
1708 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001709 if (dict == NULL)
1710 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001711 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001712 if (list == NULL || !PyList_Check(list))
1713 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001714 i = PyList_GET_SIZE(list);
1715 /* Count backwards because we always expect obj to be list[-1] */
1716 while (--i >= 0) {
1717 if (PyList_GET_ITEM(list, i) == obj) {
1718 PyList_SetSlice(list, i, i + 1, NULL);
1719 break;
1720 }
1721 }
1722}
Guido van Rossumd724b232000-03-13 16:01:29 +00001723
1724/*
1725 trashcan
1726 CT 2k0130
1727 non-recursively destroy nested objects
1728
1729 CT 2k0223
1730 everything is now done in a macro.
1731
1732 CT 2k0305
1733 modified to use functions, after Tim Peter's suggestion.
1734
1735 CT 2k0309
1736 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001737
1738 CT 2k0325
1739 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00001740
1741 CT 2k0422
1742 complete rewrite. We now build a chain via ob_type
1743 and save the limited number of types in ob_refcnt.
1744 This is perfect since we don't need any memory.
1745 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00001746*/
1747
Guido van Rossume92e6102000-04-24 15:40:53 +00001748#define Py_TRASHCAN_TUPLE 1
1749#define Py_TRASHCAN_LIST 2
1750#define Py_TRASHCAN_DICT 3
1751#define Py_TRASHCAN_FRAME 4
1752#define Py_TRASHCAN_TRACEBACK 5
1753/* extend here if other objects want protection */
1754
Guido van Rossumd724b232000-03-13 16:01:29 +00001755int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001756
Guido van Rossumd724b232000-03-13 16:01:29 +00001757PyObject * _PyTrash_delete_later = NULL;
1758
1759void
Fred Drake100814d2000-07-09 15:48:49 +00001760_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001761{
Guido van Rossume92e6102000-04-24 15:40:53 +00001762 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00001763
Guido van Rossume92e6102000-04-24 15:40:53 +00001764 if (PyTuple_Check(op))
1765 typecode = Py_TRASHCAN_TUPLE;
1766 else if (PyList_Check(op))
1767 typecode = Py_TRASHCAN_LIST;
1768 else if (PyDict_Check(op))
1769 typecode = Py_TRASHCAN_DICT;
1770 else if (PyFrame_Check(op))
1771 typecode = Py_TRASHCAN_FRAME;
1772 else if (PyTraceBack_Check(op))
1773 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00001774 else /* We have a bug here -- those are the only types in GC */ {
1775 Py_FatalError("Type not supported in GC -- internal bug");
1776 return; /* pacify compiler -- execution never here */
1777 }
Guido van Rossume92e6102000-04-24 15:40:53 +00001778 op->ob_refcnt = typecode;
Guido van Rossumd724b232000-03-13 16:01:29 +00001779
Guido van Rossume92e6102000-04-24 15:40:53 +00001780 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
1781 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001782}
1783
1784void
Fred Drake100814d2000-07-09 15:48:49 +00001785_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001786{
1787 while (_PyTrash_delete_later) {
1788 PyObject *shredder = _PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001789 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
1790
1791 switch (shredder->ob_refcnt) {
1792 case Py_TRASHCAN_TUPLE:
1793 shredder->ob_type = &PyTuple_Type;
1794 break;
1795 case Py_TRASHCAN_LIST:
1796 shredder->ob_type = &PyList_Type;
1797 break;
1798 case Py_TRASHCAN_DICT:
1799 shredder->ob_type = &PyDict_Type;
1800 break;
1801 case Py_TRASHCAN_FRAME:
1802 shredder->ob_type = &PyFrame_Type;
1803 break;
1804 case Py_TRASHCAN_TRACEBACK:
1805 shredder->ob_type = &PyTraceBack_Type;
1806 break;
1807 }
1808 _Py_NewReference(shredder);
1809
Guido van Rossumd724b232000-03-13 16:01:29 +00001810 ++_PyTrash_delete_nesting;
1811 Py_DECREF(shredder);
1812 --_PyTrash_delete_nesting;
1813 }
1814}
Neil Schemenauera35c6882001-02-27 04:45:05 +00001815
1816#ifdef WITH_PYMALLOC
1817#include "obmalloc.c"
1818#endif