blob: 3207d8a556e551367d380df231a980c010bf87a6 [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 Rossuma4073002002-05-31 20:03:54 +0000356/* Helper to warn about deprecated tp_compare return values. Return:
357 -2 for an exception;
358 -1 if v < w;
359 0 if v == w;
360 1 if v > w.
361 (This function cannot return 2.)
362*/
363static int
364adjust_tp_compare(int c)
365{
366 if (PyErr_Occurred()) {
367 if (c != -1 && c != -2) {
368 PyObject *t, *v, *tb;
369 PyErr_Fetch(&t, &v, &tb);
370 if (PyErr_Warn(PyExc_RuntimeWarning,
371 "tp_compare didn't return -1 or -2 "
372 "for exception") < 0) {
373 Py_XDECREF(t);
374 Py_XDECREF(v);
375 Py_XDECREF(tb);
376 }
377 else
378 PyErr_Restore(t, v, tb);
379 }
380 return -2;
381 }
382 else if (c < -1 || c > 1) {
383 if (PyErr_Warn(PyExc_RuntimeWarning,
384 "tp_compare didn't return -1, 0 or 1") < 0)
385 return -2;
386 else
387 return c < -1 ? -1 : 1;
388 }
389 else {
390 assert(c >= -1 && c <= 1);
391 return c;
392 }
393}
394
395
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000396/* Macro to get the tp_richcompare field of a type if defined */
397#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
398 ? (t)->tp_richcompare : NULL)
399
Guido van Rossume797ec12001-01-17 15:24:28 +0000400/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
401static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000402
Guido van Rossume797ec12001-01-17 15:24:28 +0000403/* Try a genuine rich comparison, returning an object. Return:
404 NULL for exception;
405 NotImplemented if this particular rich comparison is not implemented or
406 undefined;
407 some object not equal to NotImplemented if it is implemented
408 (this latter object may not be a Boolean).
409*/
410static PyObject *
411try_rich_compare(PyObject *v, PyObject *w, int op)
412{
413 richcmpfunc f;
414 PyObject *res;
415
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000416 if (v->ob_type != w->ob_type &&
417 PyType_IsSubtype(w->ob_type, v->ob_type) &&
418 (f = RICHCOMPARE(w->ob_type)) != NULL) {
419 res = (*f)(w, v, swapped_op[op]);
420 if (res != Py_NotImplemented)
421 return res;
422 Py_DECREF(res);
423 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000424 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000425 res = (*f)(v, w, op);
426 if (res != Py_NotImplemented)
427 return res;
428 Py_DECREF(res);
429 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000430 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000431 return (*f)(w, v, swapped_op[op]);
432 }
433 res = Py_NotImplemented;
434 Py_INCREF(res);
435 return res;
436}
437
438/* Try a genuine rich comparison, returning an int. Return:
439 -1 for exception (including the case where try_rich_compare() returns an
440 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000441 0 if the outcome is false;
442 1 if the outcome is true;
443 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000444*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000445static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000446try_rich_compare_bool(PyObject *v, PyObject *w, int op)
447{
448 PyObject *res;
449 int ok;
450
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000451 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000452 return 2; /* Shortcut, avoid INCREF+DECREF */
453 res = try_rich_compare(v, w, op);
454 if (res == NULL)
455 return -1;
456 if (res == Py_NotImplemented) {
457 Py_DECREF(res);
458 return 2;
459 }
460 ok = PyObject_IsTrue(res);
461 Py_DECREF(res);
462 return ok;
463}
464
465/* Try rich comparisons to determine a 3-way comparison. Return:
466 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000467 -1 if v < w;
468 0 if v == w;
469 1 if v > w;
470 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000471*/
472static int
473try_rich_to_3way_compare(PyObject *v, PyObject *w)
474{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000475 static struct { int op; int outcome; } tries[3] = {
476 /* Try this operator, and if it is true, use this outcome: */
477 {Py_EQ, 0},
478 {Py_LT, -1},
479 {Py_GT, 1},
480 };
481 int i;
482
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000483 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000484 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000485
486 for (i = 0; i < 3; i++) {
487 switch (try_rich_compare_bool(v, w, tries[i].op)) {
488 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000489 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000490 case 1:
491 return tries[i].outcome;
492 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000493 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000494
495 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000496}
497
498/* Try a 3-way comparison, returning an int. Return:
499 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000500 -1 if v < w;
501 0 if v == w;
502 1 if v > w;
503 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000504*/
505static int
506try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000507{
508 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000509 cmpfunc f;
510
511 /* Comparisons involving instances are given to instance_compare,
512 which has the same return conventions as this function. */
513
Guido van Rossumab3b0342001-09-18 20:38:53 +0000514 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000515 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000516 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000517 if (PyInstance_Check(w))
518 return (*w->ob_type->tp_compare)(v, w);
519
Guido van Rossumab3b0342001-09-18 20:38:53 +0000520 /* If both have the same (non-NULL) tp_compare, use it. */
521 if (f != NULL && f == w->ob_type->tp_compare) {
522 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000523 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000524 }
525
526 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
527 if (f == _PyObject_SlotCompare ||
528 w->ob_type->tp_compare == _PyObject_SlotCompare)
529 return _PyObject_SlotCompare(v, w);
530
Guido van Rossume797ec12001-01-17 15:24:28 +0000531 /* Try coercion; if it fails, give up */
532 c = PyNumber_CoerceEx(&v, &w);
533 if (c < 0)
534 return -2;
535 if (c > 0)
536 return 2;
537
538 /* Try v's comparison, if defined */
539 if ((f = v->ob_type->tp_compare) != NULL) {
540 c = (*f)(v, w);
541 Py_DECREF(v);
542 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000543 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000544 }
545
546 /* Try w's comparison, if defined */
547 if ((f = w->ob_type->tp_compare) != NULL) {
548 c = (*f)(w, v); /* swapped! */
549 Py_DECREF(v);
550 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000551 c = adjust_tp_compare(c);
552 if (c >= -1)
553 return -c; /* Swapped! */
554 else
555 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000556 }
557
558 /* No comparison defined */
559 Py_DECREF(v);
560 Py_DECREF(w);
561 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000562}
563
Guido van Rossume797ec12001-01-17 15:24:28 +0000564/* Final fallback 3-way comparison, returning an int. Return:
565 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000566 -1 if v < w;
567 0 if v == w;
568 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000569*/
570static int
571default_3way_compare(PyObject *v, PyObject *w)
572{
573 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000574 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000575
576 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000577 /* When comparing these pointers, they must be cast to
578 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
579 * uintptr_t). ANSI specifies that pointer compares other
580 * than == and != to non-related structures are undefined.
581 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000582 Py_uintptr_t vv = (Py_uintptr_t)v;
583 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000584 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
585 }
586
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000587#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000588 /* Special case for Unicode */
589 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
590 c = PyUnicode_Compare(v, w);
591 if (!PyErr_Occurred())
592 return c;
593 /* TypeErrors are ignored: if Unicode coercion fails due
594 to one of the arguments not having the right type, we
595 continue as defined by the coercion protocol (see
596 above). Luckily, decoding errors are reported as
597 ValueErrors and are not masked by this technique. */
598 if (!PyErr_ExceptionMatches(PyExc_TypeError))
599 return -2;
600 PyErr_Clear();
601 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000602#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000603
Guido van Rossum0871e932001-01-22 19:28:09 +0000604 /* None is smaller than anything */
605 if (v == Py_None)
606 return -1;
607 if (w == Py_None)
608 return 1;
609
Guido van Rossume797ec12001-01-17 15:24:28 +0000610 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000611 if (v->ob_type->tp_as_number)
612 vname = "";
613 else
614 vname = v->ob_type->tp_name;
615 if (w->ob_type->tp_as_number)
616 wname = "";
617 else
618 wname = w->ob_type->tp_name;
619 c = strcmp(vname, wname);
620 if (c < 0)
621 return -1;
622 if (c > 0)
623 return 1;
624 /* Same type name, or (more likely) incomparable numeric types */
625 return ((Py_uintptr_t)(v->ob_type) < (
626 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000627}
628
629#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
630
Tim Peters6d60b2e2001-05-07 20:53:51 +0000631/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000632 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000633 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000634 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000635 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000636 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000637 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000638*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000639static int
Fred Drake100814d2000-07-09 15:48:49 +0000640do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000641{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000642 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000643 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000644
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000645 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000646 && (f = v->ob_type->tp_compare) != NULL) {
647 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000648 if (PyInstance_Check(v)) {
649 /* Instance tp_compare has a different signature.
650 But if it returns undefined we fall through. */
651 if (c != 2)
652 return c;
653 /* Else fall throug to try_rich_to_3way_compare() */
654 }
655 else
656 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000657 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000658 /* We only get here if one of the following is true:
659 a) v and w have different types
660 b) v and w have the same type, which doesn't have tp_compare
661 c) v and w are instances, and either __cmp__ is not defined or
662 __cmp__ returns NotImplemented
663 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000664 c = try_rich_to_3way_compare(v, w);
665 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000666 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000667 c = try_3way_compare(v, w);
668 if (c < 2)
669 return c;
670 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000671}
672
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000673/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000674 some types) and decremented on exit. If the count exceeds the
675 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000676
677 This is a tunable parameter that should only affect the performance
678 of comparisons, nothing else. Setting it high makes comparing deeply
679 nested non-cyclical data structures faster, but makes comparing cyclical
680 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000681*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000682#define NESTING_LIMIT 20
683
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000684static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000685
686static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000687get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000688{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000689 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000690 PyObject *tstate_dict, *inprogress;
691
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000692 if (key == NULL) {
693 key = PyString_InternFromString("cmp_state");
694 if (key == NULL)
695 return NULL;
696 }
697
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000698 tstate_dict = PyThreadState_GetDict();
699 if (tstate_dict == NULL) {
700 PyErr_BadInternalCall();
701 return NULL;
702 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000703
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000704 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000705 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000706 inprogress = PyDict_New();
707 if (inprogress == NULL)
708 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000709 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000710 Py_DECREF(inprogress);
711 return NULL;
712 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000713 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000714 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000715
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000716 return inprogress;
717}
718
719static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000720check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000721{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000722 PyObject *inprogress;
723 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000724 Py_uintptr_t iv = (Py_uintptr_t)v;
725 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000726 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000727
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000728 inprogress = get_inprogress_dict();
729 if (inprogress == NULL)
730 return NULL;
731
732 token = PyTuple_New(3);
733 if (token == NULL)
734 return NULL;
735
736 if (iv <= iw) {
737 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
738 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
739 if (op >= 0)
740 op = swapped_op[op];
741 } else {
742 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
743 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
744 }
745 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
746 if (x == NULL || y == NULL || z == NULL) {
747 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000748 return NULL;
749 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000750
751 if (PyDict_GetItem(inprogress, token) != NULL) {
752 Py_DECREF(token);
753 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000754 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000755
756 if (PyDict_SetItem(inprogress, token, token) < 0) {
757 Py_DECREF(token);
758 return NULL;
759 }
760
761 return token;
762}
763
764static void
765delete_token(PyObject *token)
766{
767 PyObject *inprogress;
768
769 if (token == NULL || token == Py_None)
770 return;
771 inprogress = get_inprogress_dict();
772 if (inprogress == NULL)
773 PyErr_Clear();
774 else
775 PyDict_DelItem(inprogress, token);
776 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000777}
778
Tim Petersc99213f2001-11-04 05:57:16 +0000779/* Compare v to w. Return
780 -1 if v < w or exception (PyErr_Occurred() true in latter case).
781 0 if v == w.
782 1 if v > w.
783 XXX The docs (C API manual) say the return value is undefined in case
784 XXX of error.
785*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786int
Fred Drake100814d2000-07-09 15:48:49 +0000787PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000788{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000789 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000790 int result;
791
Jack Jansend49cbe12000-08-22 21:52:51 +0000792#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000793 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000794 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000795 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000796 }
797#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000798 if (v == NULL || w == NULL) {
799 PyErr_BadInternalCall();
800 return -1;
801 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802 if (v == w)
803 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000804 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000805 compare_nesting++;
806 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000807 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000808 || (vtp->tp_as_sequence
809 && !PyString_Check(v)
810 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000811 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000812 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000813
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000814 if (token == NULL) {
815 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000816 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000817 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000818 /* already comparing these objects. assume
819 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000820 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000821 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000822 else {
823 result = do_cmp(v, w);
824 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000825 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000826 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000827 else {
828 result = do_cmp(v, w);
829 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000830 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000831 return result < 0 ? -1 : result;
832}
833
Tim Petersc99213f2001-11-04 05:57:16 +0000834/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000835static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000836convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000837{
Guido van Rossume797ec12001-01-17 15:24:28 +0000838 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000839 switch (op) {
840 case Py_LT: c = c < 0; break;
841 case Py_LE: c = c <= 0; break;
842 case Py_EQ: c = c == 0; break;
843 case Py_NE: c = c != 0; break;
844 case Py_GT: c = c > 0; break;
845 case Py_GE: c = c >= 0; break;
846 }
847 result = c ? Py_True : Py_False;
848 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000849 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000850}
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000851
Tim Petersc99213f2001-11-04 05:57:16 +0000852/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
853 Return
854 NULL if error
855 Py_True if v op w
856 Py_False if not (v op w)
857*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000858static PyObject *
859try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
860{
861 int c;
862
863 c = try_3way_compare(v, w);
864 if (c >= 2)
865 c = default_3way_compare(v, w);
866 if (c <= -2)
867 return NULL;
868 return convert_3way_to_object(op, c);
869}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000870
Tim Petersc99213f2001-11-04 05:57:16 +0000871/* Do rich comparison on v and w. Return
872 NULL if error
873 Else a new reference to an object other than Py_NotImplemented, usually(?):
874 Py_True if v op w
875 Py_False if not (v op w)
876*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000877static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000878do_richcmp(PyObject *v, PyObject *w, int op)
879{
880 PyObject *res;
881
882 res = try_rich_compare(v, w, op);
883 if (res != Py_NotImplemented)
884 return res;
885 Py_DECREF(res);
886
887 return try_3way_to_rich_compare(v, w, op);
888}
889
Tim Petersc99213f2001-11-04 05:57:16 +0000890/* Return:
891 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000892 some object not equal to NotImplemented if it is implemented
893 (this latter object may not be a Boolean).
894*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000895PyObject *
896PyObject_RichCompare(PyObject *v, PyObject *w, int op)
897{
898 PyObject *res;
899
900 assert(Py_LT <= op && op <= Py_GE);
901
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000902 compare_nesting++;
903 if (compare_nesting > NESTING_LIMIT &&
904 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000905 || (v->ob_type->tp_as_sequence
906 && !PyString_Check(v)
907 && !PyTuple_Check(v)))) {
Tim Peters67754e92001-11-04 07:29:31 +0000908
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000909 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000910 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000911 if (token == NULL) {
912 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000913 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000914 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000915 else if (token == Py_None) {
916 /* already comparing these objects with this operator.
917 assume they're equal until shown otherwise */
918 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000919 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000920 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000921 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000922 else {
923 PyErr_SetString(PyExc_ValueError,
924 "can't order recursive values");
925 res = NULL;
926 }
927 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000928 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000929 else {
930 res = do_richcmp(v, w, op);
931 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000932 }
Tim Peters67754e92001-11-04 07:29:31 +0000933 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000934 }
Tim Peters67754e92001-11-04 07:29:31 +0000935
936 /* No nesting extremism.
937 If the types are equal, and not old-style instances, try to
938 get out cheap (don't bother with coercions etc.). */
939 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
940 cmpfunc fcmp;
941 richcmpfunc frich = RICHCOMPARE(v->ob_type);
942 /* If the type has richcmp, try it first. try_rich_compare
943 tries it two-sided, which is not needed since we've a
944 single type only. */
945 if (frich != NULL) {
946 res = (*frich)(v, w, op);
947 if (res != Py_NotImplemented)
948 goto Done;
949 Py_DECREF(res);
950 }
951 /* No richcmp, or this particular richmp not implemented.
952 Try 3-way cmp. */
953 fcmp = v->ob_type->tp_compare;
954 if (fcmp != NULL) {
955 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000956 c = adjust_tp_compare(c);
957 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000958 res = NULL;
959 goto Done;
960 }
961 res = convert_3way_to_object(op, c);
962 goto Done;
963 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000964 }
Tim Peters67754e92001-11-04 07:29:31 +0000965
966 /* Fast path not taken, or couldn't deliver a useful result. */
967 res = do_richcmp(v, w, op);
968Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000969 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000970 return res;
971}
972
Tim Petersde9725f2001-05-05 10:06:17 +0000973/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000974int
975PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
976{
977 PyObject *res = PyObject_RichCompare(v, w, op);
978 int ok;
979
980 if (res == NULL)
981 return -1;
982 ok = PyObject_IsTrue(res);
983 Py_DECREF(res);
984 return ok;
985}
Fred Drake13634cf2000-06-29 19:17:04 +0000986
987/* Set of hash utility functions to help maintaining the invariant that
988 iff a==b then hash(a)==hash(b)
989
990 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
991*/
992
993long
Fred Drake100814d2000-07-09 15:48:49 +0000994_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000995{
Tim Peters39dce292000-08-15 03:34:48 +0000996 double intpart, fractpart;
997 int expo;
998 long hipart;
999 long x; /* the final hash value */
1000 /* This is designed so that Python numbers of different types
1001 * that compare equal hash to the same value; otherwise comparisons
1002 * of mapping keys will turn out weird.
1003 */
1004
1005#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1006{
1007 extended e;
1008 fractpart = modf(v, &e);
1009 intpart = e;
1010}
1011#else
1012 fractpart = modf(v, &intpart);
1013#endif
1014 if (fractpart == 0.0) {
1015 /* This must return the same hash as an equal int or long. */
1016 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1017 /* Convert to long and use its hash. */
1018 PyObject *plong; /* converted to Python long */
1019 if (Py_IS_INFINITY(intpart))
1020 /* can't convert to long int -- arbitrary */
1021 v = v < 0 ? -271828.0 : 314159.0;
1022 plong = PyLong_FromDouble(v);
1023 if (plong == NULL)
1024 return -1;
1025 x = PyObject_Hash(plong);
1026 Py_DECREF(plong);
1027 return x;
1028 }
1029 /* Fits in a C long == a Python int, so is its own hash. */
1030 x = (long)intpart;
1031 if (x == -1)
1032 x = -2;
1033 return x;
1034 }
1035 /* The fractional part is non-zero, so we don't have to worry about
1036 * making this match the hash of some other type.
1037 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001038 * Since the VAX D double format has 56 mantissa bits, which is the
1039 * most of any double format in use, each of these parts may have as
1040 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001041 * So, assuming sizeof(long) >= 4, each part can be broken into two
1042 * longs; frexp and multiplication are used to do that.
1043 * Also, since the Cray double format has 15 exponent bits, which is
1044 * the most of any double format in use, shifting the exponent field
1045 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001046 */
Tim Peters39dce292000-08-15 03:34:48 +00001047 v = frexp(v, &expo);
1048 v *= 2147483648.0; /* 2**31 */
1049 hipart = (long)v; /* take the top 32 bits */
1050 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1051 x = hipart + (long)v + (expo << 15);
1052 if (x == -1)
1053 x = -2;
1054 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001055}
1056
1057long
Fred Drake100814d2000-07-09 15:48:49 +00001058_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001059{
1060#if SIZEOF_LONG >= SIZEOF_VOID_P
1061 return (long)p;
1062#else
1063 /* convert to a Python long and hash that */
1064 PyObject* longobj;
1065 long x;
1066
1067 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1068 x = -1;
1069 goto finally;
1070 }
1071 x = PyObject_Hash(longobj);
1072
1073finally:
1074 Py_XDECREF(longobj);
1075 return x;
1076#endif
1077}
1078
1079
Guido van Rossum9bfef441993-03-29 10:43:31 +00001080long
Fred Drake100814d2000-07-09 15:48:49 +00001081PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001082{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001083 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001084 if (tp->tp_hash != NULL)
1085 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001086 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001087 return _Py_HashPointer(v); /* Use address as hash value */
1088 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001089 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001090 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001091 return -1;
1092}
1093
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001094PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001095PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001096{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001097 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001098
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001100 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 w = PyString_InternFromString(name);
1102 if (w == NULL)
1103 return NULL;
1104 res = PyObject_GetAttr(v, w);
1105 Py_XDECREF(w);
1106 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001107}
1108
1109int
Fred Drake100814d2000-07-09 15:48:49 +00001110PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001111{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001112 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001113 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001114 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001115 return 1;
1116 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001117 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001118 return 0;
1119}
1120
1121int
Fred Drake100814d2000-07-09 15:48:49 +00001122PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001123{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124 PyObject *s;
1125 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001126
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001128 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001129 s = PyString_InternFromString(name);
1130 if (s == NULL)
1131 return -1;
1132 res = PyObject_SetAttr(v, s, w);
1133 Py_XDECREF(s);
1134 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001135}
1136
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001137PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001138PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001139{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 PyTypeObject *tp = v->ob_type;
1141
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001142 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001143#ifdef Py_USING_UNICODE
1144 /* The Unicode to string conversion is done here because the
1145 existing tp_getattro slots expect a string object as name
1146 and we wouldn't want to break those. */
1147 if (PyUnicode_Check(name)) {
1148 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1149 if (name == NULL)
1150 return NULL;
1151 }
1152 else
1153#endif
1154 {
1155 PyErr_SetString(PyExc_TypeError,
1156 "attribute name must be string");
1157 return NULL;
1158 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001159 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160 if (tp->tp_getattro != NULL)
1161 return (*tp->tp_getattro)(v, name);
1162 if (tp->tp_getattr != NULL)
1163 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1164 PyErr_Format(PyExc_AttributeError,
1165 "'%.50s' object has no attribute '%.400s'",
1166 tp->tp_name, PyString_AS_STRING(name));
1167 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001168}
1169
1170int
Fred Drake100814d2000-07-09 15:48:49 +00001171PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001172{
1173 PyObject *res = PyObject_GetAttr(v, name);
1174 if (res != NULL) {
1175 Py_DECREF(res);
1176 return 1;
1177 }
1178 PyErr_Clear();
1179 return 0;
1180}
1181
1182int
Fred Drake100814d2000-07-09 15:48:49 +00001183PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001184{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001186 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001187
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001188 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001189#ifdef Py_USING_UNICODE
1190 /* The Unicode to string conversion is done here because the
1191 existing tp_setattro slots expect a string object as name
1192 and we wouldn't want to break those. */
1193 if (PyUnicode_Check(name)) {
1194 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1195 if (name == NULL)
1196 return -1;
1197 }
1198 else
1199#endif
1200 {
1201 PyErr_SetString(PyExc_TypeError,
1202 "attribute name must be string");
1203 return -1;
1204 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001205 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206 else
1207 Py_INCREF(name);
1208
1209 PyString_InternInPlace(&name);
1210 if (tp->tp_setattro != NULL) {
1211 err = (*tp->tp_setattro)(v, name, value);
1212 Py_DECREF(name);
1213 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001214 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001215 if (tp->tp_setattr != NULL) {
1216 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1217 Py_DECREF(name);
1218 return err;
1219 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001220 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1222 PyErr_Format(PyExc_TypeError,
1223 "'%.100s' object has no attributes "
1224 "(%s .%.100s)",
1225 tp->tp_name,
1226 value==NULL ? "del" : "assign to",
1227 PyString_AS_STRING(name));
1228 else
1229 PyErr_Format(PyExc_TypeError,
1230 "'%.100s' object has only read-only attributes "
1231 "(%s .%.100s)",
1232 tp->tp_name,
1233 value==NULL ? "del" : "assign to",
1234 PyString_AS_STRING(name));
1235 return -1;
1236}
1237
1238/* Helper to get a pointer to an object's __dict__ slot, if any */
1239
1240PyObject **
1241_PyObject_GetDictPtr(PyObject *obj)
1242{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 long dictoffset;
1244 PyTypeObject *tp = obj->ob_type;
1245
1246 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1247 return NULL;
1248 dictoffset = tp->tp_dictoffset;
1249 if (dictoffset == 0)
1250 return NULL;
1251 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001252 int tsize;
1253 size_t size;
1254
1255 tsize = ((PyVarObject *)obj)->ob_size;
1256 if (tsize < 0)
1257 tsize = -tsize;
1258 size = _PyObject_VAR_SIZE(tp, tsize);
1259
Tim Peters6d483d32001-10-06 21:27:34 +00001260 dictoffset += (long)size;
1261 assert(dictoffset > 0);
1262 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 }
1264 return (PyObject **) ((char *)obj + dictoffset);
1265}
1266
1267/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1268
1269PyObject *
1270PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1271{
1272 PyTypeObject *tp = obj->ob_type;
1273 PyObject *descr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001274 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 descrgetfunc f;
1276 PyObject **dictptr;
1277
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001278 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001279#ifdef Py_USING_UNICODE
1280 /* The Unicode to string conversion is done here because the
1281 existing tp_setattro slots expect a string object as name
1282 and we wouldn't want to break those. */
1283 if (PyUnicode_Check(name)) {
1284 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1285 if (name == NULL)
1286 return NULL;
1287 }
1288 else
1289#endif
1290 {
1291 PyErr_SetString(PyExc_TypeError,
1292 "attribute name must be string");
1293 return NULL;
1294 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001295 }
1296 else
1297 Py_INCREF(name);
1298
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001300 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001301 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302 }
1303
1304 descr = _PyType_Lookup(tp, name);
1305 f = NULL;
1306 if (descr != NULL) {
1307 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001308 if (f != NULL && PyDescr_IsData(descr)) {
1309 res = f(descr, obj, (PyObject *)obj->ob_type);
1310 goto done;
1311 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312 }
1313
1314 dictptr = _PyObject_GetDictPtr(obj);
1315 if (dictptr != NULL) {
1316 PyObject *dict = *dictptr;
1317 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001318 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 if (res != NULL) {
1320 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001321 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 }
1323 }
1324 }
1325
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001326 if (f != NULL) {
1327 res = f(descr, obj, (PyObject *)obj->ob_type);
1328 goto done;
1329 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330
1331 if (descr != NULL) {
1332 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001333 res = descr;
1334 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 }
1336
1337 PyErr_Format(PyExc_AttributeError,
1338 "'%.50s' object has no attribute '%.400s'",
1339 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001340 done:
1341 Py_DECREF(name);
1342 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343}
1344
1345int
1346PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1347{
1348 PyTypeObject *tp = obj->ob_type;
1349 PyObject *descr;
1350 descrsetfunc f;
1351 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001352 int res = -1;
1353
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001354 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001355#ifdef Py_USING_UNICODE
1356 /* The Unicode to string conversion is done here because the
1357 existing tp_setattro slots expect a string object as name
1358 and we wouldn't want to break those. */
1359 if (PyUnicode_Check(name)) {
1360 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1361 if (name == NULL)
1362 return -1;
1363 }
1364 else
1365#endif
1366 {
1367 PyErr_SetString(PyExc_TypeError,
1368 "attribute name must be string");
1369 return -1;
1370 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001371 }
1372 else
1373 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001374
1375 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001376 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001377 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378 }
1379
1380 descr = _PyType_Lookup(tp, name);
1381 f = NULL;
1382 if (descr != NULL) {
1383 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001384 if (f != NULL && PyDescr_IsData(descr)) {
1385 res = f(descr, obj, value);
1386 goto done;
1387 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 }
1389
1390 dictptr = _PyObject_GetDictPtr(obj);
1391 if (dictptr != NULL) {
1392 PyObject *dict = *dictptr;
1393 if (dict == NULL && value != NULL) {
1394 dict = PyDict_New();
1395 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001396 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 *dictptr = dict;
1398 }
1399 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001400 if (value == NULL)
1401 res = PyDict_DelItem(dict, name);
1402 else
1403 res = PyDict_SetItem(dict, name, value);
1404 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1405 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001406 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 }
1408 }
1409
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001410 if (f != NULL) {
1411 res = f(descr, obj, value);
1412 goto done;
1413 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001414
1415 if (descr == NULL) {
1416 PyErr_Format(PyExc_AttributeError,
1417 "'%.50s' object has no attribute '%.400s'",
1418 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001419 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420 }
1421
1422 PyErr_Format(PyExc_AttributeError,
1423 "'%.50s' object attribute '%.400s' is read-only",
1424 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001425 done:
1426 Py_DECREF(name);
1427 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001428}
1429
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001430/* Test a value used as condition, e.g., in a for or if statement.
1431 Return -1 if an error occurred */
1432
1433int
Fred Drake100814d2000-07-09 15:48:49 +00001434PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001435{
1436 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001437 if (v == Py_None)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001438 res = 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001439 else if (v->ob_type->tp_as_number != NULL &&
1440 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001441 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001442 else if (v->ob_type->tp_as_mapping != NULL &&
1443 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001444 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001445 else if (v->ob_type->tp_as_sequence != NULL &&
1446 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001447 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1448 else
1449 res = 1;
1450 if (res > 0)
1451 res = 1;
1452 return res;
1453}
1454
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001455/* equivalent of 'not v'
1456 Return -1 if an error occurred */
1457
1458int
Fred Drake100814d2000-07-09 15:48:49 +00001459PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001460{
1461 int res;
1462 res = PyObject_IsTrue(v);
1463 if (res < 0)
1464 return res;
1465 return res == 0;
1466}
1467
Guido van Rossum5524a591995-01-10 15:26:20 +00001468/* Coerce two numeric types to the "larger" one.
1469 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001470 Return value:
1471 -1 if an error occurred;
1472 0 if the coercion succeeded (and then the reference counts are increased);
1473 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001474*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001475int
Fred Drake100814d2000-07-09 15:48:49 +00001476PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001477{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001478 register PyObject *v = *pv;
1479 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001480 int res;
1481
Guido van Rossum517c7d42002-04-26 02:49:14 +00001482 /* Shortcut only for old-style types */
1483 if (v->ob_type == w->ob_type &&
1484 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1485 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001486 Py_INCREF(v);
1487 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001488 return 0;
1489 }
1490 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1491 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1492 if (res <= 0)
1493 return res;
1494 }
1495 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1496 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1497 if (res <= 0)
1498 return res;
1499 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001500 return 1;
1501}
1502
Guido van Rossume797ec12001-01-17 15:24:28 +00001503/* Coerce two numeric types to the "larger" one.
1504 Increment the reference count on each argument.
1505 Return -1 and raise an exception if no coercion is possible
1506 (and then no reference count is incremented).
1507*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001508int
Fred Drake100814d2000-07-09 15:48:49 +00001509PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001510{
1511 int err = PyNumber_CoerceEx(pv, pw);
1512 if (err <= 0)
1513 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001514 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001515 return -1;
1516}
1517
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001518
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001519/* Test whether an object can be called */
1520
1521int
Fred Drake100814d2000-07-09 15:48:49 +00001522PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001523{
1524 if (x == NULL)
1525 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001526 if (PyInstance_Check(x)) {
1527 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001528 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001529 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001530 return 0;
1531 }
1532 /* Could test recursively but don't, for fear of endless
1533 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001534 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001535 return 1;
1536 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001537 else {
1538 return x->ob_type->tp_call != NULL;
1539 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001540}
1541
Tim Peters7eea37e2001-09-04 22:08:56 +00001542/* Helper for PyObject_Dir.
1543 Merge the __dict__ of aclass into dict, and recursively also all
1544 the __dict__s of aclass's base classes. The order of merging isn't
1545 defined, as it's expected that only the final set of dict keys is
1546 interesting.
1547 Return 0 on success, -1 on error.
1548*/
1549
1550static int
1551merge_class_dict(PyObject* dict, PyObject* aclass)
1552{
1553 PyObject *classdict;
1554 PyObject *bases;
1555
1556 assert(PyDict_Check(dict));
1557 assert(aclass);
1558
1559 /* Merge in the type's dict (if any). */
1560 classdict = PyObject_GetAttrString(aclass, "__dict__");
1561 if (classdict == NULL)
1562 PyErr_Clear();
1563 else {
1564 int status = PyDict_Update(dict, classdict);
1565 Py_DECREF(classdict);
1566 if (status < 0)
1567 return -1;
1568 }
1569
1570 /* Recursively merge in the base types' (if any) dicts. */
1571 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001572 if (bases == NULL)
1573 PyErr_Clear();
1574 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001575 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001576 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001577 n = PySequence_Size(bases); /* This better be right */
1578 if (n < 0)
1579 PyErr_Clear();
1580 else {
1581 for (i = 0; i < n; i++) {
1582 PyObject *base = PySequence_GetItem(bases, i);
1583 if (base == NULL) {
1584 Py_DECREF(bases);
1585 return -1;
1586 }
1587 if (merge_class_dict(dict, base) < 0) {
1588 Py_DECREF(bases);
1589 return -1;
1590 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001591 }
1592 }
1593 Py_DECREF(bases);
1594 }
1595 return 0;
1596}
1597
Tim Peters305b5852001-09-17 02:38:46 +00001598/* Helper for PyObject_Dir.
1599 If obj has an attr named attrname that's a list, merge its string
1600 elements into keys of dict.
1601 Return 0 on success, -1 on error. Errors due to not finding the attr,
1602 or the attr not being a list, are suppressed.
1603*/
1604
1605static int
1606merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1607{
1608 PyObject *list;
1609 int result = 0;
1610
1611 assert(PyDict_Check(dict));
1612 assert(obj);
1613 assert(attrname);
1614
1615 list = PyObject_GetAttrString(obj, attrname);
1616 if (list == NULL)
1617 PyErr_Clear();
1618
1619 else if (PyList_Check(list)) {
1620 int i;
1621 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1622 PyObject *item = PyList_GET_ITEM(list, i);
1623 if (PyString_Check(item)) {
1624 result = PyDict_SetItem(dict, item, Py_None);
1625 if (result < 0)
1626 break;
1627 }
1628 }
1629 }
1630
1631 Py_XDECREF(list);
1632 return result;
1633}
1634
Tim Peters7eea37e2001-09-04 22:08:56 +00001635/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1636 docstring, which should be kept in synch with this implementation. */
1637
1638PyObject *
1639PyObject_Dir(PyObject *arg)
1640{
1641 /* Set exactly one of these non-NULL before the end. */
1642 PyObject *result = NULL; /* result list */
1643 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1644
1645 /* If NULL arg, return the locals. */
1646 if (arg == NULL) {
1647 PyObject *locals = PyEval_GetLocals();
1648 if (locals == NULL)
1649 goto error;
1650 result = PyDict_Keys(locals);
1651 if (result == NULL)
1652 goto error;
1653 }
1654
1655 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001656 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001657 masterdict = PyObject_GetAttrString(arg, "__dict__");
1658 if (masterdict == NULL)
1659 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001660 if (!PyDict_Check(masterdict)) {
1661 PyErr_SetString(PyExc_TypeError,
1662 "module.__dict__ is not a dictionary");
1663 goto error;
1664 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001665 }
1666
1667 /* Elif some form of type or class, grab its dict and its bases.
1668 We deliberately don't suck up its __class__, as methods belonging
1669 to the metaclass would probably be more confusing than helpful. */
1670 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1671 masterdict = PyDict_New();
1672 if (masterdict == NULL)
1673 goto error;
1674 if (merge_class_dict(masterdict, arg) < 0)
1675 goto error;
1676 }
1677
1678 /* Else look at its dict, and the attrs reachable from its class. */
1679 else {
1680 PyObject *itsclass;
1681 /* Create a dict to start with. CAUTION: Not everything
1682 responding to __dict__ returns a dict! */
1683 masterdict = PyObject_GetAttrString(arg, "__dict__");
1684 if (masterdict == NULL) {
1685 PyErr_Clear();
1686 masterdict = PyDict_New();
1687 }
1688 else if (!PyDict_Check(masterdict)) {
1689 Py_DECREF(masterdict);
1690 masterdict = PyDict_New();
1691 }
1692 else {
1693 /* The object may have returned a reference to its
1694 dict, so copy it to avoid mutating it. */
1695 PyObject *temp = PyDict_Copy(masterdict);
1696 Py_DECREF(masterdict);
1697 masterdict = temp;
1698 }
1699 if (masterdict == NULL)
1700 goto error;
1701
Tim Peters305b5852001-09-17 02:38:46 +00001702 /* Merge in __members__ and __methods__ (if any).
1703 XXX Would like this to go away someday; for now, it's
1704 XXX needed to get at im_self etc of method objects. */
1705 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1706 goto error;
1707 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1708 goto error;
1709
Tim Peters7eea37e2001-09-04 22:08:56 +00001710 /* Merge in attrs reachable from its class.
1711 CAUTION: Not all objects have a __class__ attr. */
1712 itsclass = PyObject_GetAttrString(arg, "__class__");
1713 if (itsclass == NULL)
1714 PyErr_Clear();
1715 else {
1716 int status = merge_class_dict(masterdict, itsclass);
1717 Py_DECREF(itsclass);
1718 if (status < 0)
1719 goto error;
1720 }
1721 }
1722
1723 assert((result == NULL) ^ (masterdict == NULL));
1724 if (masterdict != NULL) {
1725 /* The result comes from its keys. */
1726 assert(result == NULL);
1727 result = PyDict_Keys(masterdict);
1728 if (result == NULL)
1729 goto error;
1730 }
1731
1732 assert(result);
1733 if (PyList_Sort(result) != 0)
1734 goto error;
1735 else
1736 goto normal_return;
1737
1738 error:
1739 Py_XDECREF(result);
1740 result = NULL;
1741 /* fall through */
1742 normal_return:
1743 Py_XDECREF(masterdict);
1744 return result;
1745}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001746
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001747/*
1748NoObject is usable as a non-NULL undefined value, used by the macro None.
1749There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001750so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001751(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001752*/
1753
Guido van Rossum0c182a11992-03-27 17:26:13 +00001754/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001755static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001756none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001757{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001758 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001759}
1760
Barry Warsaw9bf16442001-01-23 16:24:35 +00001761/* ARGUSED */
1762static void
1763none_dealloc(PyObject* ignore)
1764{
1765 /* This should never get called, but we also don't want to SEGV if
1766 * we accidently decref None out of existance.
1767 */
1768 abort();
1769}
1770
1771
Guido van Rossumba21a492001-08-16 08:17:26 +00001772static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001773 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001774 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001775 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001776 0,
1777 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001778 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001779 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001780 0, /*tp_getattr*/
1781 0, /*tp_setattr*/
1782 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001783 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001784 0, /*tp_as_number*/
1785 0, /*tp_as_sequence*/
1786 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001787 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001788};
1789
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001790PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001791 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001792};
1793
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001794/* NotImplemented is an object that can be used to signal that an
1795 operation is not implemented for the given type combination. */
1796
1797static PyObject *
1798NotImplemented_repr(PyObject *op)
1799{
1800 return PyString_FromString("NotImplemented");
1801}
1802
1803static PyTypeObject PyNotImplemented_Type = {
1804 PyObject_HEAD_INIT(&PyType_Type)
1805 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001806 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001807 0,
1808 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001809 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001810 0, /*tp_print*/
1811 0, /*tp_getattr*/
1812 0, /*tp_setattr*/
1813 0, /*tp_compare*/
1814 (reprfunc)NotImplemented_repr, /*tp_repr*/
1815 0, /*tp_as_number*/
1816 0, /*tp_as_sequence*/
1817 0, /*tp_as_mapping*/
1818 0, /*tp_hash */
1819};
1820
1821PyObject _Py_NotImplementedStruct = {
1822 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1823};
1824
Guido van Rossumba21a492001-08-16 08:17:26 +00001825void
1826_Py_ReadyTypes(void)
1827{
1828 if (PyType_Ready(&PyType_Type) < 0)
1829 Py_FatalError("Can't initialize 'type'");
1830
Guido van Rossum77f6a652002-04-03 22:41:51 +00001831 if (PyType_Ready(&PyBool_Type) < 0)
1832 Py_FatalError("Can't initialize 'bool'");
1833
Guido van Rossumcacfc072002-05-24 19:01:59 +00001834 if (PyType_Ready(&PyString_Type) < 0)
1835 Py_FatalError("Can't initialize 'str'");
1836
Guido van Rossumba21a492001-08-16 08:17:26 +00001837 if (PyType_Ready(&PyList_Type) < 0)
1838 Py_FatalError("Can't initialize 'list'");
1839
1840 if (PyType_Ready(&PyNone_Type) < 0)
1841 Py_FatalError("Can't initialize type(None)");
1842
1843 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1844 Py_FatalError("Can't initialize type(NotImplemented)");
1845}
1846
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847
Guido van Rossum84a90321996-05-22 16:34:47 +00001848#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001852void
Fred Drake100814d2000-07-09 15:48:49 +00001853_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001854{
1855 refchain._ob_prev = refchain._ob_next = &refchain;
1856 _Py_RefTotal = 0;
1857}
1858
1859void
Fred Drake100814d2000-07-09 15:48:49 +00001860_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001861{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001862 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001863 op->ob_refcnt = 1;
1864 op->_ob_next = refchain._ob_next;
1865 op->_ob_prev = &refchain;
1866 refchain._ob_next->_ob_prev = op;
1867 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001868#ifdef COUNT_ALLOCS
1869 inc_count(op->ob_type);
1870#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001871}
1872
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001873void
Fred Drake100814d2000-07-09 15:48:49 +00001874_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001875{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001876#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001877 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001878#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001879 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001880 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001881 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001882 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001883 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001884#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001885 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1886 if (p == op)
1887 break;
1888 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001889 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001890 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001891#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892 op->_ob_next->_ob_prev = op->_ob_prev;
1893 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001894 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001895#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001896 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001897#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001898}
1899
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001900void
Fred Drake100814d2000-07-09 15:48:49 +00001901_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001902{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001903 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001904 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001905 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001906}
1907
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001908void
Fred Drake100814d2000-07-09 15:48:49 +00001909_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001910{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001912 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001913 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1914 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001915 if (PyObject_Print(op, fp, 0) != 0)
1916 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001917 putc('\n', fp);
1918 }
1919}
1920
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001921PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001922_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001923{
1924 int i, n;
1925 PyObject *t = NULL;
1926 PyObject *res, *op;
1927
1928 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1929 return NULL;
1930 op = refchain._ob_next;
1931 res = PyList_New(0);
1932 if (res == NULL)
1933 return NULL;
1934 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1935 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001936 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001937 op = op->_ob_next;
1938 if (op == &refchain)
1939 return res;
1940 }
1941 if (PyList_Append(res, op) < 0) {
1942 Py_DECREF(res);
1943 return NULL;
1944 }
1945 op = op->_ob_next;
1946 }
1947 return res;
1948}
1949
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001950#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001951
1952
1953/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001954PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001955
1956
1957/* Hack to force loading of abstract.o */
Jeremy Hylton6253f832000-07-12 12:56:19 +00001958int (*_Py_abstract_hack)(PyObject *) = &PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001959
1960
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001961/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001962
Thomas Wouters334fb892000-07-25 12:56:38 +00001963void *
Fred Drake100814d2000-07-09 15:48:49 +00001964PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001965{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001966 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001967}
1968
Thomas Wouters334fb892000-07-25 12:56:38 +00001969void *
1970PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001971{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001972 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001973}
1974
1975void
Thomas Wouters334fb892000-07-25 12:56:38 +00001976PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001977{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001978 PyMem_FREE(p);
1979}
1980
1981
Guido van Rossum86610361998-04-10 22:32:46 +00001982/* These methods are used to control infinite recursion in repr, str, print,
1983 etc. Container objects that may recursively contain themselves,
1984 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1985 Py_ReprLeave() to avoid infinite recursion.
1986
1987 Py_ReprEnter() returns 0 the first time it is called for a particular
1988 object and 1 every time thereafter. It returns -1 if an exception
1989 occurred. Py_ReprLeave() has no return value.
1990
1991 See dictobject.c and listobject.c for examples of use.
1992*/
1993
1994#define KEY "Py_Repr"
1995
1996int
Fred Drake100814d2000-07-09 15:48:49 +00001997Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001998{
1999 PyObject *dict;
2000 PyObject *list;
2001 int i;
2002
2003 dict = PyThreadState_GetDict();
2004 if (dict == NULL)
2005 return -1;
2006 list = PyDict_GetItemString(dict, KEY);
2007 if (list == NULL) {
2008 list = PyList_New(0);
2009 if (list == NULL)
2010 return -1;
2011 if (PyDict_SetItemString(dict, KEY, list) < 0)
2012 return -1;
2013 Py_DECREF(list);
2014 }
2015 i = PyList_GET_SIZE(list);
2016 while (--i >= 0) {
2017 if (PyList_GET_ITEM(list, i) == obj)
2018 return 1;
2019 }
2020 PyList_Append(list, obj);
2021 return 0;
2022}
2023
2024void
Fred Drake100814d2000-07-09 15:48:49 +00002025Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002026{
2027 PyObject *dict;
2028 PyObject *list;
2029 int i;
2030
2031 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002032 if (dict == NULL)
2033 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002034 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002035 if (list == NULL || !PyList_Check(list))
2036 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002037 i = PyList_GET_SIZE(list);
2038 /* Count backwards because we always expect obj to be list[-1] */
2039 while (--i >= 0) {
2040 if (PyList_GET_ITEM(list, i) == obj) {
2041 PyList_SetSlice(list, i, i + 1, NULL);
2042 break;
2043 }
2044 }
2045}
Guido van Rossumd724b232000-03-13 16:01:29 +00002046
2047/*
2048 trashcan
2049 CT 2k0130
2050 non-recursively destroy nested objects
2051
2052 CT 2k0223
2053 everything is now done in a macro.
2054
2055 CT 2k0305
2056 modified to use functions, after Tim Peter's suggestion.
2057
2058 CT 2k0309
2059 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00002060
2061 CT 2k0325
2062 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00002063
2064 CT 2k0422
2065 complete rewrite. We now build a chain via ob_type
2066 and save the limited number of types in ob_refcnt.
2067 This is perfect since we don't need any memory.
2068 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00002069*/
2070
Guido van Rossume92e6102000-04-24 15:40:53 +00002071#define Py_TRASHCAN_TUPLE 1
2072#define Py_TRASHCAN_LIST 2
2073#define Py_TRASHCAN_DICT 3
2074#define Py_TRASHCAN_FRAME 4
2075#define Py_TRASHCAN_TRACEBACK 5
2076/* extend here if other objects want protection */
2077
Guido van Rossumd724b232000-03-13 16:01:29 +00002078int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002079
Guido van Rossumd724b232000-03-13 16:01:29 +00002080PyObject * _PyTrash_delete_later = NULL;
2081
2082void
Fred Drake100814d2000-07-09 15:48:49 +00002083_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002084{
Neil Schemenauerf589c052002-03-29 03:05:54 +00002085#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002086 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00002087
Guido van Rossume92e6102000-04-24 15:40:53 +00002088 if (PyTuple_Check(op))
2089 typecode = Py_TRASHCAN_TUPLE;
2090 else if (PyList_Check(op))
2091 typecode = Py_TRASHCAN_LIST;
2092 else if (PyDict_Check(op))
2093 typecode = Py_TRASHCAN_DICT;
2094 else if (PyFrame_Check(op))
2095 typecode = Py_TRASHCAN_FRAME;
2096 else if (PyTraceBack_Check(op))
2097 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00002098 else /* We have a bug here -- those are the only types in GC */ {
2099 Py_FatalError("Type not supported in GC -- internal bug");
2100 return; /* pacify compiler -- execution never here */
2101 }
Guido van Rossume92e6102000-04-24 15:40:53 +00002102 op->ob_refcnt = typecode;
Guido van Rossume92e6102000-04-24 15:40:53 +00002103 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002104#else
2105 assert (_Py_AS_GC(op)->gc.gc_next == NULL);
2106 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2107#endif
Guido van Rossume92e6102000-04-24 15:40:53 +00002108 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002109}
2110
2111void
Fred Drake100814d2000-07-09 15:48:49 +00002112_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002113{
2114 while (_PyTrash_delete_later) {
2115 PyObject *shredder = _PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002116
2117#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002118 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
2119
2120 switch (shredder->ob_refcnt) {
2121 case Py_TRASHCAN_TUPLE:
2122 shredder->ob_type = &PyTuple_Type;
2123 break;
2124 case Py_TRASHCAN_LIST:
2125 shredder->ob_type = &PyList_Type;
2126 break;
2127 case Py_TRASHCAN_DICT:
2128 shredder->ob_type = &PyDict_Type;
2129 break;
2130 case Py_TRASHCAN_FRAME:
2131 shredder->ob_type = &PyFrame_Type;
2132 break;
2133 case Py_TRASHCAN_TRACEBACK:
2134 shredder->ob_type = &PyTraceBack_Type;
2135 break;
2136 }
Neil Schemenauerf589c052002-03-29 03:05:54 +00002137#else
2138 _PyTrash_delete_later =
2139 (PyObject*) _Py_AS_GC(shredder)->gc.gc_prev;
2140#endif
2141
Guido van Rossume92e6102000-04-24 15:40:53 +00002142 _Py_NewReference(shredder);
2143
Guido van Rossumd724b232000-03-13 16:01:29 +00002144 ++_PyTrash_delete_nesting;
2145 Py_DECREF(shredder);
2146 --_PyTrash_delete_nesting;
2147 }
2148}