blob: 206746b9184b315e374596806575f94d681e5d1d [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;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000653 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000654 }
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)
Neal Norwitz51290d32002-06-13 21:32:44 +00001438 return 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
Neal Norwitz51290d32002-06-13 21:32:44 +00001449 return 1;
1450 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001451}
1452
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001453/* equivalent of 'not v'
1454 Return -1 if an error occurred */
1455
1456int
Fred Drake100814d2000-07-09 15:48:49 +00001457PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001458{
1459 int res;
1460 res = PyObject_IsTrue(v);
1461 if (res < 0)
1462 return res;
1463 return res == 0;
1464}
1465
Guido van Rossum5524a591995-01-10 15:26:20 +00001466/* Coerce two numeric types to the "larger" one.
1467 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001468 Return value:
1469 -1 if an error occurred;
1470 0 if the coercion succeeded (and then the reference counts are increased);
1471 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001472*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001473int
Fred Drake100814d2000-07-09 15:48:49 +00001474PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001475{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001476 register PyObject *v = *pv;
1477 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001478 int res;
1479
Guido van Rossum517c7d42002-04-26 02:49:14 +00001480 /* Shortcut only for old-style types */
1481 if (v->ob_type == w->ob_type &&
1482 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1483 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 Py_INCREF(v);
1485 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001486 return 0;
1487 }
1488 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1489 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1490 if (res <= 0)
1491 return res;
1492 }
1493 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1494 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1495 if (res <= 0)
1496 return res;
1497 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001498 return 1;
1499}
1500
Guido van Rossume797ec12001-01-17 15:24:28 +00001501/* Coerce two numeric types to the "larger" one.
1502 Increment the reference count on each argument.
1503 Return -1 and raise an exception if no coercion is possible
1504 (and then no reference count is incremented).
1505*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001506int
Fred Drake100814d2000-07-09 15:48:49 +00001507PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001508{
1509 int err = PyNumber_CoerceEx(pv, pw);
1510 if (err <= 0)
1511 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001512 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001513 return -1;
1514}
1515
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001516
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001517/* Test whether an object can be called */
1518
1519int
Fred Drake100814d2000-07-09 15:48:49 +00001520PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001521{
1522 if (x == NULL)
1523 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001524 if (PyInstance_Check(x)) {
1525 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001526 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001527 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001528 return 0;
1529 }
1530 /* Could test recursively but don't, for fear of endless
1531 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001532 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001533 return 1;
1534 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535 else {
1536 return x->ob_type->tp_call != NULL;
1537 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001538}
1539
Tim Peters7eea37e2001-09-04 22:08:56 +00001540/* Helper for PyObject_Dir.
1541 Merge the __dict__ of aclass into dict, and recursively also all
1542 the __dict__s of aclass's base classes. The order of merging isn't
1543 defined, as it's expected that only the final set of dict keys is
1544 interesting.
1545 Return 0 on success, -1 on error.
1546*/
1547
1548static int
1549merge_class_dict(PyObject* dict, PyObject* aclass)
1550{
1551 PyObject *classdict;
1552 PyObject *bases;
1553
1554 assert(PyDict_Check(dict));
1555 assert(aclass);
1556
1557 /* Merge in the type's dict (if any). */
1558 classdict = PyObject_GetAttrString(aclass, "__dict__");
1559 if (classdict == NULL)
1560 PyErr_Clear();
1561 else {
1562 int status = PyDict_Update(dict, classdict);
1563 Py_DECREF(classdict);
1564 if (status < 0)
1565 return -1;
1566 }
1567
1568 /* Recursively merge in the base types' (if any) dicts. */
1569 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001570 if (bases == NULL)
1571 PyErr_Clear();
1572 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001573 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001574 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001575 n = PySequence_Size(bases); /* This better be right */
1576 if (n < 0)
1577 PyErr_Clear();
1578 else {
1579 for (i = 0; i < n; i++) {
1580 PyObject *base = PySequence_GetItem(bases, i);
1581 if (base == NULL) {
1582 Py_DECREF(bases);
1583 return -1;
1584 }
1585 if (merge_class_dict(dict, base) < 0) {
1586 Py_DECREF(bases);
1587 return -1;
1588 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001589 }
1590 }
1591 Py_DECREF(bases);
1592 }
1593 return 0;
1594}
1595
Tim Peters305b5852001-09-17 02:38:46 +00001596/* Helper for PyObject_Dir.
1597 If obj has an attr named attrname that's a list, merge its string
1598 elements into keys of dict.
1599 Return 0 on success, -1 on error. Errors due to not finding the attr,
1600 or the attr not being a list, are suppressed.
1601*/
1602
1603static int
1604merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1605{
1606 PyObject *list;
1607 int result = 0;
1608
1609 assert(PyDict_Check(dict));
1610 assert(obj);
1611 assert(attrname);
1612
1613 list = PyObject_GetAttrString(obj, attrname);
1614 if (list == NULL)
1615 PyErr_Clear();
1616
1617 else if (PyList_Check(list)) {
1618 int i;
1619 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1620 PyObject *item = PyList_GET_ITEM(list, i);
1621 if (PyString_Check(item)) {
1622 result = PyDict_SetItem(dict, item, Py_None);
1623 if (result < 0)
1624 break;
1625 }
1626 }
1627 }
1628
1629 Py_XDECREF(list);
1630 return result;
1631}
1632
Tim Peters7eea37e2001-09-04 22:08:56 +00001633/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1634 docstring, which should be kept in synch with this implementation. */
1635
1636PyObject *
1637PyObject_Dir(PyObject *arg)
1638{
1639 /* Set exactly one of these non-NULL before the end. */
1640 PyObject *result = NULL; /* result list */
1641 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1642
1643 /* If NULL arg, return the locals. */
1644 if (arg == NULL) {
1645 PyObject *locals = PyEval_GetLocals();
1646 if (locals == NULL)
1647 goto error;
1648 result = PyDict_Keys(locals);
1649 if (result == NULL)
1650 goto error;
1651 }
1652
1653 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001654 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001655 masterdict = PyObject_GetAttrString(arg, "__dict__");
1656 if (masterdict == NULL)
1657 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001658 if (!PyDict_Check(masterdict)) {
1659 PyErr_SetString(PyExc_TypeError,
1660 "module.__dict__ is not a dictionary");
1661 goto error;
1662 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001663 }
1664
1665 /* Elif some form of type or class, grab its dict and its bases.
1666 We deliberately don't suck up its __class__, as methods belonging
1667 to the metaclass would probably be more confusing than helpful. */
1668 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1669 masterdict = PyDict_New();
1670 if (masterdict == NULL)
1671 goto error;
1672 if (merge_class_dict(masterdict, arg) < 0)
1673 goto error;
1674 }
1675
1676 /* Else look at its dict, and the attrs reachable from its class. */
1677 else {
1678 PyObject *itsclass;
1679 /* Create a dict to start with. CAUTION: Not everything
1680 responding to __dict__ returns a dict! */
1681 masterdict = PyObject_GetAttrString(arg, "__dict__");
1682 if (masterdict == NULL) {
1683 PyErr_Clear();
1684 masterdict = PyDict_New();
1685 }
1686 else if (!PyDict_Check(masterdict)) {
1687 Py_DECREF(masterdict);
1688 masterdict = PyDict_New();
1689 }
1690 else {
1691 /* The object may have returned a reference to its
1692 dict, so copy it to avoid mutating it. */
1693 PyObject *temp = PyDict_Copy(masterdict);
1694 Py_DECREF(masterdict);
1695 masterdict = temp;
1696 }
1697 if (masterdict == NULL)
1698 goto error;
1699
Tim Peters305b5852001-09-17 02:38:46 +00001700 /* Merge in __members__ and __methods__ (if any).
1701 XXX Would like this to go away someday; for now, it's
1702 XXX needed to get at im_self etc of method objects. */
1703 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1704 goto error;
1705 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1706 goto error;
1707
Tim Peters7eea37e2001-09-04 22:08:56 +00001708 /* Merge in attrs reachable from its class.
1709 CAUTION: Not all objects have a __class__ attr. */
1710 itsclass = PyObject_GetAttrString(arg, "__class__");
1711 if (itsclass == NULL)
1712 PyErr_Clear();
1713 else {
1714 int status = merge_class_dict(masterdict, itsclass);
1715 Py_DECREF(itsclass);
1716 if (status < 0)
1717 goto error;
1718 }
1719 }
1720
1721 assert((result == NULL) ^ (masterdict == NULL));
1722 if (masterdict != NULL) {
1723 /* The result comes from its keys. */
1724 assert(result == NULL);
1725 result = PyDict_Keys(masterdict);
1726 if (result == NULL)
1727 goto error;
1728 }
1729
1730 assert(result);
1731 if (PyList_Sort(result) != 0)
1732 goto error;
1733 else
1734 goto normal_return;
1735
1736 error:
1737 Py_XDECREF(result);
1738 result = NULL;
1739 /* fall through */
1740 normal_return:
1741 Py_XDECREF(masterdict);
1742 return result;
1743}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001744
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001745/*
1746NoObject is usable as a non-NULL undefined value, used by the macro None.
1747There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001748so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001749(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750*/
1751
Guido van Rossum0c182a11992-03-27 17:26:13 +00001752/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001753static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001754none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001755{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001756 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001757}
1758
Barry Warsaw9bf16442001-01-23 16:24:35 +00001759/* ARGUSED */
1760static void
1761none_dealloc(PyObject* ignore)
1762{
1763 /* This should never get called, but we also don't want to SEGV if
1764 * we accidently decref None out of existance.
1765 */
1766 abort();
1767}
1768
1769
Guido van Rossumba21a492001-08-16 08:17:26 +00001770static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001771 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001772 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001773 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001774 0,
1775 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001776 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001777 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001778 0, /*tp_getattr*/
1779 0, /*tp_setattr*/
1780 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001781 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001782 0, /*tp_as_number*/
1783 0, /*tp_as_sequence*/
1784 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001785 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001786};
1787
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001788PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001789 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001790};
1791
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001792/* NotImplemented is an object that can be used to signal that an
1793 operation is not implemented for the given type combination. */
1794
1795static PyObject *
1796NotImplemented_repr(PyObject *op)
1797{
1798 return PyString_FromString("NotImplemented");
1799}
1800
1801static PyTypeObject PyNotImplemented_Type = {
1802 PyObject_HEAD_INIT(&PyType_Type)
1803 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001804 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001805 0,
1806 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001807 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001808 0, /*tp_print*/
1809 0, /*tp_getattr*/
1810 0, /*tp_setattr*/
1811 0, /*tp_compare*/
1812 (reprfunc)NotImplemented_repr, /*tp_repr*/
1813 0, /*tp_as_number*/
1814 0, /*tp_as_sequence*/
1815 0, /*tp_as_mapping*/
1816 0, /*tp_hash */
1817};
1818
1819PyObject _Py_NotImplementedStruct = {
1820 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1821};
1822
Guido van Rossumba21a492001-08-16 08:17:26 +00001823void
1824_Py_ReadyTypes(void)
1825{
1826 if (PyType_Ready(&PyType_Type) < 0)
1827 Py_FatalError("Can't initialize 'type'");
1828
Guido van Rossum77f6a652002-04-03 22:41:51 +00001829 if (PyType_Ready(&PyBool_Type) < 0)
1830 Py_FatalError("Can't initialize 'bool'");
1831
Guido van Rossumcacfc072002-05-24 19:01:59 +00001832 if (PyType_Ready(&PyString_Type) < 0)
1833 Py_FatalError("Can't initialize 'str'");
1834
Guido van Rossumba21a492001-08-16 08:17:26 +00001835 if (PyType_Ready(&PyList_Type) < 0)
1836 Py_FatalError("Can't initialize 'list'");
1837
1838 if (PyType_Ready(&PyNone_Type) < 0)
1839 Py_FatalError("Can't initialize type(None)");
1840
1841 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1842 Py_FatalError("Can't initialize type(NotImplemented)");
1843}
1844
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001845
Guido van Rossum84a90321996-05-22 16:34:47 +00001846#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001848static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001850void
Fred Drake100814d2000-07-09 15:48:49 +00001851_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001852{
1853 refchain._ob_prev = refchain._ob_next = &refchain;
1854 _Py_RefTotal = 0;
1855}
1856
1857void
Fred Drake100814d2000-07-09 15:48:49 +00001858_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001859{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001860 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001861 op->ob_refcnt = 1;
1862 op->_ob_next = refchain._ob_next;
1863 op->_ob_prev = &refchain;
1864 refchain._ob_next->_ob_prev = op;
1865 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001866#ifdef COUNT_ALLOCS
1867 inc_count(op->ob_type);
1868#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001869}
1870
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001871void
Fred Drake100814d2000-07-09 15:48:49 +00001872_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001873{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001874#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001875 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001876#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001877 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001878 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001879 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001880 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001881 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001882#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001883 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1884 if (p == op)
1885 break;
1886 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001887 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001888 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001889#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001890 op->_ob_next->_ob_prev = op->_ob_prev;
1891 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001892 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001893#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001895#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001896}
1897
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001898void
Fred Drake100814d2000-07-09 15:48:49 +00001899_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001900{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001901 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001902 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001903 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001904}
1905
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001906void
Fred Drake100814d2000-07-09 15:48:49 +00001907_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001908{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001909 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001910 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001911 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1912 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001913 if (PyObject_Print(op, fp, 0) != 0)
1914 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001915 putc('\n', fp);
1916 }
1917}
1918
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001919PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001920_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001921{
1922 int i, n;
1923 PyObject *t = NULL;
1924 PyObject *res, *op;
1925
1926 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1927 return NULL;
1928 op = refchain._ob_next;
1929 res = PyList_New(0);
1930 if (res == NULL)
1931 return NULL;
1932 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1933 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001934 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001935 op = op->_ob_next;
1936 if (op == &refchain)
1937 return res;
1938 }
1939 if (PyList_Append(res, op) < 0) {
1940 Py_DECREF(res);
1941 return NULL;
1942 }
1943 op = op->_ob_next;
1944 }
1945 return res;
1946}
1947
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001948#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001949
1950
1951/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001952PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001953
1954
1955/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001956int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001957
1958
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001959/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001960
Thomas Wouters334fb892000-07-25 12:56:38 +00001961void *
Fred Drake100814d2000-07-09 15:48:49 +00001962PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001963{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001964 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001965}
1966
Thomas Wouters334fb892000-07-25 12:56:38 +00001967void *
1968PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001969{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001970 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001971}
1972
1973void
Thomas Wouters334fb892000-07-25 12:56:38 +00001974PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001975{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001976 PyMem_FREE(p);
1977}
1978
1979
Guido van Rossum86610361998-04-10 22:32:46 +00001980/* These methods are used to control infinite recursion in repr, str, print,
1981 etc. Container objects that may recursively contain themselves,
1982 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1983 Py_ReprLeave() to avoid infinite recursion.
1984
1985 Py_ReprEnter() returns 0 the first time it is called for a particular
1986 object and 1 every time thereafter. It returns -1 if an exception
1987 occurred. Py_ReprLeave() has no return value.
1988
1989 See dictobject.c and listobject.c for examples of use.
1990*/
1991
1992#define KEY "Py_Repr"
1993
1994int
Fred Drake100814d2000-07-09 15:48:49 +00001995Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001996{
1997 PyObject *dict;
1998 PyObject *list;
1999 int i;
2000
2001 dict = PyThreadState_GetDict();
2002 if (dict == NULL)
2003 return -1;
2004 list = PyDict_GetItemString(dict, KEY);
2005 if (list == NULL) {
2006 list = PyList_New(0);
2007 if (list == NULL)
2008 return -1;
2009 if (PyDict_SetItemString(dict, KEY, list) < 0)
2010 return -1;
2011 Py_DECREF(list);
2012 }
2013 i = PyList_GET_SIZE(list);
2014 while (--i >= 0) {
2015 if (PyList_GET_ITEM(list, i) == obj)
2016 return 1;
2017 }
2018 PyList_Append(list, obj);
2019 return 0;
2020}
2021
2022void
Fred Drake100814d2000-07-09 15:48:49 +00002023Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002024{
2025 PyObject *dict;
2026 PyObject *list;
2027 int i;
2028
2029 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002030 if (dict == NULL)
2031 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002032 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002033 if (list == NULL || !PyList_Check(list))
2034 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002035 i = PyList_GET_SIZE(list);
2036 /* Count backwards because we always expect obj to be list[-1] */
2037 while (--i >= 0) {
2038 if (PyList_GET_ITEM(list, i) == obj) {
2039 PyList_SetSlice(list, i, i + 1, NULL);
2040 break;
2041 }
2042 }
2043}
Guido van Rossumd724b232000-03-13 16:01:29 +00002044
2045/*
2046 trashcan
2047 CT 2k0130
2048 non-recursively destroy nested objects
2049
2050 CT 2k0223
2051 everything is now done in a macro.
2052
2053 CT 2k0305
2054 modified to use functions, after Tim Peter's suggestion.
2055
2056 CT 2k0309
2057 modified to restore a possible error.
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00002058
2059 CT 2k0325
2060 added better safe than sorry check for threadstate
Guido van Rossume92e6102000-04-24 15:40:53 +00002061
2062 CT 2k0422
2063 complete rewrite. We now build a chain via ob_type
2064 and save the limited number of types in ob_refcnt.
2065 This is perfect since we don't need any memory.
2066 A patch for free-threading would need just a lock.
Guido van Rossumd724b232000-03-13 16:01:29 +00002067*/
2068
Guido van Rossume92e6102000-04-24 15:40:53 +00002069#define Py_TRASHCAN_TUPLE 1
2070#define Py_TRASHCAN_LIST 2
2071#define Py_TRASHCAN_DICT 3
2072#define Py_TRASHCAN_FRAME 4
2073#define Py_TRASHCAN_TRACEBACK 5
2074/* extend here if other objects want protection */
2075
Guido van Rossumd724b232000-03-13 16:01:29 +00002076int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002077
Guido van Rossumd724b232000-03-13 16:01:29 +00002078PyObject * _PyTrash_delete_later = NULL;
2079
2080void
Fred Drake100814d2000-07-09 15:48:49 +00002081_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002082{
Neil Schemenauerf589c052002-03-29 03:05:54 +00002083#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002084 int typecode;
Guido van Rossum13ff8eb2000-03-25 18:39:19 +00002085
Guido van Rossume92e6102000-04-24 15:40:53 +00002086 if (PyTuple_Check(op))
2087 typecode = Py_TRASHCAN_TUPLE;
2088 else if (PyList_Check(op))
2089 typecode = Py_TRASHCAN_LIST;
2090 else if (PyDict_Check(op))
2091 typecode = Py_TRASHCAN_DICT;
2092 else if (PyFrame_Check(op))
2093 typecode = Py_TRASHCAN_FRAME;
2094 else if (PyTraceBack_Check(op))
2095 typecode = Py_TRASHCAN_TRACEBACK;
Moshe Zadkacf703f02000-08-04 15:36:13 +00002096 else /* We have a bug here -- those are the only types in GC */ {
2097 Py_FatalError("Type not supported in GC -- internal bug");
2098 return; /* pacify compiler -- execution never here */
2099 }
Guido van Rossume92e6102000-04-24 15:40:53 +00002100 op->ob_refcnt = typecode;
Guido van Rossume92e6102000-04-24 15:40:53 +00002101 op->ob_type = (PyTypeObject*)_PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002102#else
2103 assert (_Py_AS_GC(op)->gc.gc_next == NULL);
2104 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2105#endif
Guido van Rossume92e6102000-04-24 15:40:53 +00002106 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002107}
2108
2109void
Fred Drake100814d2000-07-09 15:48:49 +00002110_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002111{
2112 while (_PyTrash_delete_later) {
2113 PyObject *shredder = _PyTrash_delete_later;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002114
2115#ifndef WITH_CYCLE_GC
Guido van Rossume92e6102000-04-24 15:40:53 +00002116 _PyTrash_delete_later = (PyObject*) shredder->ob_type;
2117
2118 switch (shredder->ob_refcnt) {
2119 case Py_TRASHCAN_TUPLE:
2120 shredder->ob_type = &PyTuple_Type;
2121 break;
2122 case Py_TRASHCAN_LIST:
2123 shredder->ob_type = &PyList_Type;
2124 break;
2125 case Py_TRASHCAN_DICT:
2126 shredder->ob_type = &PyDict_Type;
2127 break;
2128 case Py_TRASHCAN_FRAME:
2129 shredder->ob_type = &PyFrame_Type;
2130 break;
2131 case Py_TRASHCAN_TRACEBACK:
2132 shredder->ob_type = &PyTraceBack_Type;
2133 break;
2134 }
Neil Schemenauerf589c052002-03-29 03:05:54 +00002135#else
2136 _PyTrash_delete_later =
2137 (PyObject*) _Py_AS_GC(shredder)->gc.gc_prev;
2138#endif
2139
Guido van Rossume92e6102000-04-24 15:40:53 +00002140 _Py_NewReference(shredder);
2141
Guido van Rossumd724b232000-03-13 16:01:29 +00002142 ++_PyTrash_delete_nesting;
2143 Py_DECREF(shredder);
2144 --_PyTrash_delete_nesting;
2145 }
2146}