blob: 5b61d84e4cbdc1f41a93b6a51ab4ef7094744e49 [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
Tim Peters34592512002-07-11 06:23:50 +00006#ifdef Py_REF_DEBUG
Mark Hammonda2905272002-07-29 13:42:14 +00007long _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Mark Hammonda2905272002-07-29 13:42:14 +000010int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000011
Guido van Rossum3f5da241990-12-20 15:06:42 +000012/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
13 These are used by the individual routines for object creation.
14 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015
Tim Peters78be7992003-03-23 02:51:01 +000016#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000017/* Head of circular doubly-linked list of all objects. These are linked
18 * together via the _ob_prev and _ob_next members of a PyObject, which
19 * exist only in a Py_TRACE_REFS build.
20 */
Tim Peters78be7992003-03-23 02:51:01 +000021static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000022
Tim Peters7571a0f2003-03-23 17:52:28 +000023/* Insert op at the front of the list of all objects. If force is true,
24 * op is added even if _ob_prev and _ob_next are non-NULL already. If
25 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
26 * force should be true if and only if op points to freshly allocated,
27 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000028 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000029 * Note that objects are normally added to the list via _Py_NewReference,
30 * which is called by PyObject_Init. Not all objects are initialized that
31 * way, though; exceptions include statically allocated type objects, and
32 * statically allocated singletons (like Py_True and Py_None).
33 */
Tim Peters36eb4df2003-03-23 03:33:13 +000034void
Tim Peters7571a0f2003-03-23 17:52:28 +000035_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000036{
Tim Peters7571a0f2003-03-23 17:52:28 +000037#ifdef Py_DEBUG
38 if (!force) {
39 /* If it's initialized memory, op must be in or out of
40 * the list unambiguously.
41 */
42 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
43 }
Tim Peters78be7992003-03-23 02:51:01 +000044#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000045 if (force || op->_ob_prev == NULL) {
46 op->_ob_next = refchain._ob_next;
47 op->_ob_prev = &refchain;
48 refchain._ob_next->_ob_prev = op;
49 refchain._ob_next = op;
50 }
51}
52#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000053
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000054#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000056extern int tuple_zero_allocs, fast_tuple_allocs;
57extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000058extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000059void
Fred Drake100814d2000-07-09 15:48:49 +000060dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000063
64 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000065 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000066 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000067 tp->tp_maxalloc);
68 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
69 fast_tuple_allocs, tuple_zero_allocs);
70 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
71 quick_int_allocs, quick_neg_int_allocs);
72 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
73 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074}
75
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000076PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000077get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000078{
79 PyTypeObject *tp;
80 PyObject *result;
81 PyObject *v;
82
83 result = PyList_New(0);
84 if (result == NULL)
85 return NULL;
86 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
88 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000089 if (v == NULL) {
90 Py_DECREF(result);
91 return NULL;
92 }
93 if (PyList_Append(result, v) < 0) {
94 Py_DECREF(v);
95 Py_DECREF(result);
96 return NULL;
97 }
98 Py_DECREF(v);
99 }
100 return result;
101}
102
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000103void
Fred Drake100814d2000-07-09 15:48:49 +0000104inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000105{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000106 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000107 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000108 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000110 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000111 /* Note that as of Python 2.2, heap-allocated type objects
112 * can go away, but this code requires that they stay alive
113 * until program exit. That's why we're careful with
114 * refcounts here. type_list gets a new reference to tp,
115 * while ownership of the reference type_list used to hold
116 * (if any) was transferred to tp->tp_next in the line above.
117 * tp is thus effectively immortal after this.
118 */
119 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000120 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000121#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000122 /* Also insert in the doubly-linked list of all objects,
123 * if not already there.
124 */
125 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000126#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000128 tp->tp_allocs++;
129 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
130 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000131}
132#endif
133
Tim Peters7c321a82002-07-09 02:57:01 +0000134#ifdef Py_REF_DEBUG
135/* Log a fatal error; doesn't return. */
136void
137_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
138{
139 char buf[300];
140
141 PyOS_snprintf(buf, sizeof(buf),
142 "%s:%i object at %p has negative ref count %i",
143 fname, lineno, op, op->ob_refcnt);
144 Py_FatalError(buf);
145}
146
147#endif /* Py_REF_DEBUG */
148
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000150PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000152 if (op == NULL)
153 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000154 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157 return op;
158}
159
Guido van Rossumb18618d2000-05-03 23:44:39 +0000160PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000161PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000162{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000163 if (op == NULL)
164 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000165 /* Any changes should be reflected in PyObject_INIT_VAR */
166 op->ob_size = size;
167 op->ob_type = tp;
168 _Py_NewReference((PyObject *)op);
169 return op;
170}
171
172PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000173_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000174{
175 PyObject *op;
176 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
177 if (op == NULL)
178 return PyErr_NoMemory();
179 return PyObject_INIT(op, tp);
180}
181
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000182PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000183_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000185 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000186 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000187 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000189 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000190 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000191}
192
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000193/* for binary compatibility with 2.2 */
194#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000195void
Fred Drake100814d2000-07-09 15:48:49 +0000196_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000197{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000198 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199}
200
Neal Norwitz1a997502003-01-13 20:13:12 +0000201/* Implementation of PyObject_Print with recursion checking */
202static int
203internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204{
Guido van Rossum278ef591991-07-27 21:40:24 +0000205 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000206 if (nesting > 10) {
207 PyErr_SetString(PyExc_RuntimeError, "print recursion");
208 return -1;
209 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000210 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000211 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000212#ifdef USE_STACKCHECK
213 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000214 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000215 return -1;
216 }
217#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000218 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000219 if (op == NULL) {
220 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221 }
Guido van Rossum90933611991-06-07 16:10:43 +0000222 else {
223 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000224 fprintf(fp, "<refcnt %u at %p>",
225 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000226 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000227 PyObject *s;
228 if (flags & Py_PRINT_RAW)
229 s = PyObject_Str(op);
230 else
231 s = PyObject_Repr(op);
232 if (s == NULL)
233 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000234 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000235 ret = internal_print(s, fp, Py_PRINT_RAW,
236 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000237 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000238 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000239 }
Guido van Rossum90933611991-06-07 16:10:43 +0000240 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000241 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000242 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000243 if (ret == 0) {
244 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000246 clearerr(fp);
247 ret = -1;
248 }
249 }
250 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251}
252
Neal Norwitz1a997502003-01-13 20:13:12 +0000253int
254PyObject_Print(PyObject *op, FILE *fp, int flags)
255{
256 return internal_print(op, fp, flags, 0);
257}
258
259
Barry Warsaw9bf16442001-01-23 16:24:35 +0000260/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000261void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000262{
Barry Warsaweefb1072001-02-22 22:39:18 +0000263 if (op == NULL)
264 fprintf(stderr, "NULL\n");
265 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000266 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000267 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000268 fprintf(stderr, "\n"
269 "type : %s\n"
270 "refcount: %d\n"
271 "address : %p\n",
272 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
273 op->ob_refcnt,
274 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000275 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000276}
Barry Warsaw903138f2001-01-23 16:33:18 +0000277
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000278PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000279PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000282 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000283#ifdef USE_STACKCHECK
284 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000285 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000286 return NULL;
287 }
288#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000289 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000291 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000292 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000293 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000294 else {
295 PyObject *res;
296 res = (*v->ob_type->tp_repr)(v);
297 if (res == NULL)
298 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000299#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000300 if (PyUnicode_Check(res)) {
301 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000302 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000303 Py_DECREF(res);
304 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000305 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000306 else
307 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000308 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000309#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000310 if (!PyString_Check(res)) {
311 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000312 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000313 res->ob_type->tp_name);
314 Py_DECREF(res);
315 return NULL;
316 }
317 return res;
318 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319}
320
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000321PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000322PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000323{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000324 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000325
Guido van Rossumc6004111993-11-05 10:22:19 +0000326 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000328 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000330 return v;
331 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000332 if (v->ob_type->tp_str == NULL)
333 return PyObject_Repr(v);
334
335 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000336 if (res == NULL)
337 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000338#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000339 if (PyUnicode_Check(res)) {
340 PyObject* str;
341 str = PyUnicode_AsEncodedString(res, NULL, NULL);
342 Py_DECREF(res);
343 if (str)
344 res = str;
345 else
346 return NULL;
347 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000348#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000349 if (!PyString_Check(res)) {
350 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000351 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000352 res->ob_type->tp_name);
353 Py_DECREF(res);
354 return NULL;
355 }
356 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000357}
358
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000359#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000360PyObject *
361PyObject_Unicode(PyObject *v)
362{
363 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000364
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000365 if (v == NULL)
366 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000367 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000368 Py_INCREF(v);
369 return v;
370 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000371 if (PyUnicode_Check(v)) {
372 /* For a Unicode subtype that's not a Unicode object,
373 return a true Unicode object with the same data. */
374 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
375 PyUnicode_GET_SIZE(v));
376 }
377 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000378 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000379 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000380 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000381 else {
382 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000383 static PyObject *unicodestr;
384 /* XXX As soon as we have a tp_unicode slot, we should
385 check this before trying the __unicode__
386 method. */
387 if (unicodestr == NULL) {
388 unicodestr= PyString_InternFromString(
389 "__unicode__");
390 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000391 return NULL;
392 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000393 func = PyObject_GetAttr(v, unicodestr);
394 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000395 res = PyEval_CallObject(func, (PyObject *)NULL);
396 Py_DECREF(func);
397 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000398 else {
399 PyErr_Clear();
400 if (v->ob_type->tp_str != NULL)
401 res = (*v->ob_type->tp_str)(v);
402 else
403 res = PyObject_Repr(v);
404 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000405 }
406 if (res == NULL)
407 return NULL;
408 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000409 PyObject *str;
410 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000411 Py_DECREF(res);
412 if (str)
413 res = str;
414 else
415 return NULL;
416 }
417 return res;
418}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000419#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000420
421
Guido van Rossuma4073002002-05-31 20:03:54 +0000422/* Helper to warn about deprecated tp_compare return values. Return:
423 -2 for an exception;
424 -1 if v < w;
425 0 if v == w;
426 1 if v > w.
427 (This function cannot return 2.)
428*/
429static int
430adjust_tp_compare(int c)
431{
432 if (PyErr_Occurred()) {
433 if (c != -1 && c != -2) {
434 PyObject *t, *v, *tb;
435 PyErr_Fetch(&t, &v, &tb);
436 if (PyErr_Warn(PyExc_RuntimeWarning,
437 "tp_compare didn't return -1 or -2 "
438 "for exception") < 0) {
439 Py_XDECREF(t);
440 Py_XDECREF(v);
441 Py_XDECREF(tb);
442 }
443 else
444 PyErr_Restore(t, v, tb);
445 }
446 return -2;
447 }
448 else if (c < -1 || c > 1) {
449 if (PyErr_Warn(PyExc_RuntimeWarning,
450 "tp_compare didn't return -1, 0 or 1") < 0)
451 return -2;
452 else
453 return c < -1 ? -1 : 1;
454 }
455 else {
456 assert(c >= -1 && c <= 1);
457 return c;
458 }
459}
460
461
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000462/* Macro to get the tp_richcompare field of a type if defined */
463#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
464 ? (t)->tp_richcompare : NULL)
465
Guido van Rossume797ec12001-01-17 15:24:28 +0000466/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
467static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000468
Guido van Rossume797ec12001-01-17 15:24:28 +0000469/* Try a genuine rich comparison, returning an object. Return:
470 NULL for exception;
471 NotImplemented if this particular rich comparison is not implemented or
472 undefined;
473 some object not equal to NotImplemented if it is implemented
474 (this latter object may not be a Boolean).
475*/
476static PyObject *
477try_rich_compare(PyObject *v, PyObject *w, int op)
478{
479 richcmpfunc f;
480 PyObject *res;
481
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000482 if (v->ob_type != w->ob_type &&
483 PyType_IsSubtype(w->ob_type, v->ob_type) &&
484 (f = RICHCOMPARE(w->ob_type)) != NULL) {
485 res = (*f)(w, v, swapped_op[op]);
486 if (res != Py_NotImplemented)
487 return res;
488 Py_DECREF(res);
489 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000490 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000491 res = (*f)(v, w, op);
492 if (res != Py_NotImplemented)
493 return res;
494 Py_DECREF(res);
495 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000496 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000497 return (*f)(w, v, swapped_op[op]);
498 }
499 res = Py_NotImplemented;
500 Py_INCREF(res);
501 return res;
502}
503
504/* Try a genuine rich comparison, returning an int. Return:
505 -1 for exception (including the case where try_rich_compare() returns an
506 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000507 0 if the outcome is false;
508 1 if the outcome is true;
509 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000510*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000511static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000512try_rich_compare_bool(PyObject *v, PyObject *w, int op)
513{
514 PyObject *res;
515 int ok;
516
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000517 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000518 return 2; /* Shortcut, avoid INCREF+DECREF */
519 res = try_rich_compare(v, w, op);
520 if (res == NULL)
521 return -1;
522 if (res == Py_NotImplemented) {
523 Py_DECREF(res);
524 return 2;
525 }
526 ok = PyObject_IsTrue(res);
527 Py_DECREF(res);
528 return ok;
529}
530
531/* Try rich comparisons to determine a 3-way comparison. Return:
532 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000533 -1 if v < w;
534 0 if v == w;
535 1 if v > w;
536 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000537*/
538static int
539try_rich_to_3way_compare(PyObject *v, PyObject *w)
540{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000541 static struct { int op; int outcome; } tries[3] = {
542 /* Try this operator, and if it is true, use this outcome: */
543 {Py_EQ, 0},
544 {Py_LT, -1},
545 {Py_GT, 1},
546 };
547 int i;
548
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000549 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000550 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000551
552 for (i = 0; i < 3; i++) {
553 switch (try_rich_compare_bool(v, w, tries[i].op)) {
554 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000555 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000556 case 1:
557 return tries[i].outcome;
558 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000559 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000560
561 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000562}
563
564/* Try a 3-way comparison, returning an int. Return:
565 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000566 -1 if v < w;
567 0 if v == w;
568 1 if v > w;
569 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000570*/
571static int
572try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000573{
574 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000575 cmpfunc f;
576
577 /* Comparisons involving instances are given to instance_compare,
578 which has the same return conventions as this function. */
579
Guido van Rossumab3b0342001-09-18 20:38:53 +0000580 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000581 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000582 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000583 if (PyInstance_Check(w))
584 return (*w->ob_type->tp_compare)(v, w);
585
Guido van Rossumab3b0342001-09-18 20:38:53 +0000586 /* If both have the same (non-NULL) tp_compare, use it. */
587 if (f != NULL && f == w->ob_type->tp_compare) {
588 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000589 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000590 }
591
592 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
593 if (f == _PyObject_SlotCompare ||
594 w->ob_type->tp_compare == _PyObject_SlotCompare)
595 return _PyObject_SlotCompare(v, w);
596
Guido van Rossume797ec12001-01-17 15:24:28 +0000597 /* Try coercion; if it fails, give up */
598 c = PyNumber_CoerceEx(&v, &w);
599 if (c < 0)
600 return -2;
601 if (c > 0)
602 return 2;
603
604 /* Try v's comparison, if defined */
605 if ((f = v->ob_type->tp_compare) != NULL) {
606 c = (*f)(v, w);
607 Py_DECREF(v);
608 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000609 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000610 }
611
612 /* Try w's comparison, if defined */
613 if ((f = w->ob_type->tp_compare) != NULL) {
614 c = (*f)(w, v); /* swapped! */
615 Py_DECREF(v);
616 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000617 c = adjust_tp_compare(c);
618 if (c >= -1)
619 return -c; /* Swapped! */
620 else
621 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000622 }
623
624 /* No comparison defined */
625 Py_DECREF(v);
626 Py_DECREF(w);
627 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000628}
629
Guido van Rossume797ec12001-01-17 15:24:28 +0000630/* Final fallback 3-way comparison, returning an int. Return:
631 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000632 -1 if v < w;
633 0 if v == w;
634 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000635*/
636static int
637default_3way_compare(PyObject *v, PyObject *w)
638{
639 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000640 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000641
642 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000643 /* When comparing these pointers, they must be cast to
644 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
645 * uintptr_t). ANSI specifies that pointer compares other
646 * than == and != to non-related structures are undefined.
647 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000648 Py_uintptr_t vv = (Py_uintptr_t)v;
649 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000650 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
651 }
652
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000653#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000654 /* Special case for Unicode */
655 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
656 c = PyUnicode_Compare(v, w);
657 if (!PyErr_Occurred())
658 return c;
659 /* TypeErrors are ignored: if Unicode coercion fails due
660 to one of the arguments not having the right type, we
661 continue as defined by the coercion protocol (see
662 above). Luckily, decoding errors are reported as
663 ValueErrors and are not masked by this technique. */
664 if (!PyErr_ExceptionMatches(PyExc_TypeError))
665 return -2;
666 PyErr_Clear();
667 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000668#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000669
Guido van Rossum0871e932001-01-22 19:28:09 +0000670 /* None is smaller than anything */
671 if (v == Py_None)
672 return -1;
673 if (w == Py_None)
674 return 1;
675
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000676 /* different type: compare type names; numbers are smaller */
677 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000678 vname = "";
679 else
680 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000681 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000682 wname = "";
683 else
684 wname = w->ob_type->tp_name;
685 c = strcmp(vname, wname);
686 if (c < 0)
687 return -1;
688 if (c > 0)
689 return 1;
690 /* Same type name, or (more likely) incomparable numeric types */
691 return ((Py_uintptr_t)(v->ob_type) < (
692 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000693}
694
695#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
696
Tim Peters6d60b2e2001-05-07 20:53:51 +0000697/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000698 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000699 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000700 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000701 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000702 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000703 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000704*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000705static int
Fred Drake100814d2000-07-09 15:48:49 +0000706do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000707{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000708 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000709 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000710
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000711 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000712 && (f = v->ob_type->tp_compare) != NULL) {
713 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000714 if (PyInstance_Check(v)) {
715 /* Instance tp_compare has a different signature.
716 But if it returns undefined we fall through. */
717 if (c != 2)
718 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000719 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000720 }
721 else
722 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000723 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000724 /* We only get here if one of the following is true:
725 a) v and w have different types
726 b) v and w have the same type, which doesn't have tp_compare
727 c) v and w are instances, and either __cmp__ is not defined or
728 __cmp__ returns NotImplemented
729 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000730 c = try_rich_to_3way_compare(v, w);
731 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000732 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000733 c = try_3way_compare(v, w);
734 if (c < 2)
735 return c;
736 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000737}
738
Tim Petersc99213f2001-11-04 05:57:16 +0000739/* Compare v to w. Return
740 -1 if v < w or exception (PyErr_Occurred() true in latter case).
741 0 if v == w.
742 1 if v > w.
743 XXX The docs (C API manual) say the return value is undefined in case
744 XXX of error.
745*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000746int
Fred Drake100814d2000-07-09 15:48:49 +0000747PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000748{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000749 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000750 int result;
751
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000752 if (v == NULL || w == NULL) {
753 PyErr_BadInternalCall();
754 return -1;
755 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756 if (v == w)
757 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000758 vtp = v->ob_type;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000759 if (Py_EnterRecursiveCall(" in cmp"))
760 return -1;
761 result = do_cmp(v, w);
762 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000763 return result < 0 ? -1 : result;
764}
765
Tim Petersc99213f2001-11-04 05:57:16 +0000766/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000767static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000768convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000769{
Guido van Rossume797ec12001-01-17 15:24:28 +0000770 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000771 switch (op) {
772 case Py_LT: c = c < 0; break;
773 case Py_LE: c = c <= 0; break;
774 case Py_EQ: c = c == 0; break;
775 case Py_NE: c = c != 0; break;
776 case Py_GT: c = c > 0; break;
777 case Py_GE: c = c >= 0; break;
778 }
779 result = c ? Py_True : Py_False;
780 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000781 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000782}
Tim Peters803526b2002-07-07 05:13:56 +0000783
Tim Petersc99213f2001-11-04 05:57:16 +0000784/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
785 Return
786 NULL if error
787 Py_True if v op w
788 Py_False if not (v op w)
789*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000790static PyObject *
791try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
792{
793 int c;
794
795 c = try_3way_compare(v, w);
796 if (c >= 2)
797 c = default_3way_compare(v, w);
798 if (c <= -2)
799 return NULL;
800 return convert_3way_to_object(op, c);
801}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802
Tim Petersc99213f2001-11-04 05:57:16 +0000803/* Do rich comparison on v and w. Return
804 NULL if error
805 Else a new reference to an object other than Py_NotImplemented, usually(?):
806 Py_True if v op w
807 Py_False if not (v op w)
808*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000809static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000810do_richcmp(PyObject *v, PyObject *w, int op)
811{
812 PyObject *res;
813
814 res = try_rich_compare(v, w, op);
815 if (res != Py_NotImplemented)
816 return res;
817 Py_DECREF(res);
818
819 return try_3way_to_rich_compare(v, w, op);
820}
821
Tim Petersc99213f2001-11-04 05:57:16 +0000822/* Return:
823 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000824 some object not equal to NotImplemented if it is implemented
825 (this latter object may not be a Boolean).
826*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000827PyObject *
828PyObject_RichCompare(PyObject *v, PyObject *w, int op)
829{
830 PyObject *res;
831
832 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000833 if (Py_EnterRecursiveCall(" in cmp"))
834 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000835
Armin Rigo2b3eb402003-10-28 12:05:48 +0000836 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000837 get out cheap (don't bother with coercions etc.). */
838 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
839 cmpfunc fcmp;
840 richcmpfunc frich = RICHCOMPARE(v->ob_type);
841 /* If the type has richcmp, try it first. try_rich_compare
842 tries it two-sided, which is not needed since we've a
843 single type only. */
844 if (frich != NULL) {
845 res = (*frich)(v, w, op);
846 if (res != Py_NotImplemented)
847 goto Done;
848 Py_DECREF(res);
849 }
850 /* No richcmp, or this particular richmp not implemented.
851 Try 3-way cmp. */
852 fcmp = v->ob_type->tp_compare;
853 if (fcmp != NULL) {
854 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000855 c = adjust_tp_compare(c);
856 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000857 res = NULL;
858 goto Done;
859 }
860 res = convert_3way_to_object(op, c);
861 goto Done;
862 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000863 }
Tim Peters67754e92001-11-04 07:29:31 +0000864
865 /* Fast path not taken, or couldn't deliver a useful result. */
866 res = do_richcmp(v, w, op);
867Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000868 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000869 return res;
870}
871
Tim Petersde9725f2001-05-05 10:06:17 +0000872/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000873int
874PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
875{
876 PyObject *res = PyObject_RichCompare(v, w, op);
877 int ok;
878
879 if (res == NULL)
880 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000881 if (PyBool_Check(res))
882 ok = (res == Py_True);
883 else
884 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000885 Py_DECREF(res);
886 return ok;
887}
Fred Drake13634cf2000-06-29 19:17:04 +0000888
889/* Set of hash utility functions to help maintaining the invariant that
890 iff a==b then hash(a)==hash(b)
891
892 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
893*/
894
895long
Fred Drake100814d2000-07-09 15:48:49 +0000896_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000897{
Tim Peters39dce292000-08-15 03:34:48 +0000898 double intpart, fractpart;
899 int expo;
900 long hipart;
901 long x; /* the final hash value */
902 /* This is designed so that Python numbers of different types
903 * that compare equal hash to the same value; otherwise comparisons
904 * of mapping keys will turn out weird.
905 */
906
Tim Peters39dce292000-08-15 03:34:48 +0000907 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000908 if (fractpart == 0.0) {
909 /* This must return the same hash as an equal int or long. */
910 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
911 /* Convert to long and use its hash. */
912 PyObject *plong; /* converted to Python long */
913 if (Py_IS_INFINITY(intpart))
914 /* can't convert to long int -- arbitrary */
915 v = v < 0 ? -271828.0 : 314159.0;
916 plong = PyLong_FromDouble(v);
917 if (plong == NULL)
918 return -1;
919 x = PyObject_Hash(plong);
920 Py_DECREF(plong);
921 return x;
922 }
923 /* Fits in a C long == a Python int, so is its own hash. */
924 x = (long)intpart;
925 if (x == -1)
926 x = -2;
927 return x;
928 }
929 /* The fractional part is non-zero, so we don't have to worry about
930 * making this match the hash of some other type.
931 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000932 * Since the VAX D double format has 56 mantissa bits, which is the
933 * most of any double format in use, each of these parts may have as
934 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000935 * So, assuming sizeof(long) >= 4, each part can be broken into two
936 * longs; frexp and multiplication are used to do that.
937 * Also, since the Cray double format has 15 exponent bits, which is
938 * the most of any double format in use, shifting the exponent field
939 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000940 */
Tim Peters39dce292000-08-15 03:34:48 +0000941 v = frexp(v, &expo);
942 v *= 2147483648.0; /* 2**31 */
943 hipart = (long)v; /* take the top 32 bits */
944 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
945 x = hipart + (long)v + (expo << 15);
946 if (x == -1)
947 x = -2;
948 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000949}
950
951long
Fred Drake100814d2000-07-09 15:48:49 +0000952_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000953{
954#if SIZEOF_LONG >= SIZEOF_VOID_P
955 return (long)p;
956#else
957 /* convert to a Python long and hash that */
958 PyObject* longobj;
959 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000960
Fred Drake13634cf2000-06-29 19:17:04 +0000961 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
962 x = -1;
963 goto finally;
964 }
965 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000966
Fred Drake13634cf2000-06-29 19:17:04 +0000967finally:
968 Py_XDECREF(longobj);
969 return x;
970#endif
971}
972
973
Guido van Rossum9bfef441993-03-29 10:43:31 +0000974long
Fred Drake100814d2000-07-09 15:48:49 +0000975PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000976{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000977 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000978 if (tp->tp_hash != NULL)
979 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000980 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000981 return _Py_HashPointer(v); /* Use address as hash value */
982 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000983 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000985 return -1;
986}
987
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000988PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000989PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000990{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000991 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000992
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000994 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995 w = PyString_InternFromString(name);
996 if (w == NULL)
997 return NULL;
998 res = PyObject_GetAttr(v, w);
999 Py_XDECREF(w);
1000 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001001}
1002
1003int
Fred Drake100814d2000-07-09 15:48:49 +00001004PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001005{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001006 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001007 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001008 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001009 return 1;
1010 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001011 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001012 return 0;
1013}
1014
1015int
Fred Drake100814d2000-07-09 15:48:49 +00001016PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001017{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018 PyObject *s;
1019 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001020
Tim Peters6d6c1a32001-08-02 04:15:00 +00001021 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001022 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001023 s = PyString_InternFromString(name);
1024 if (s == NULL)
1025 return -1;
1026 res = PyObject_SetAttr(v, s, w);
1027 Py_XDECREF(s);
1028 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001029}
1030
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001031PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001032PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001033{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001034 PyTypeObject *tp = v->ob_type;
1035
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001036 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001037#ifdef Py_USING_UNICODE
1038 /* The Unicode to string conversion is done here because the
1039 existing tp_getattro slots expect a string object as name
1040 and we wouldn't want to break those. */
1041 if (PyUnicode_Check(name)) {
1042 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1043 if (name == NULL)
1044 return NULL;
1045 }
1046 else
1047#endif
1048 {
1049 PyErr_SetString(PyExc_TypeError,
1050 "attribute name must be string");
1051 return NULL;
1052 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001053 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054 if (tp->tp_getattro != NULL)
1055 return (*tp->tp_getattro)(v, name);
1056 if (tp->tp_getattr != NULL)
1057 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1058 PyErr_Format(PyExc_AttributeError,
1059 "'%.50s' object has no attribute '%.400s'",
1060 tp->tp_name, PyString_AS_STRING(name));
1061 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001062}
1063
1064int
Fred Drake100814d2000-07-09 15:48:49 +00001065PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001066{
1067 PyObject *res = PyObject_GetAttr(v, name);
1068 if (res != NULL) {
1069 Py_DECREF(res);
1070 return 1;
1071 }
1072 PyErr_Clear();
1073 return 0;
1074}
1075
1076int
Fred Drake100814d2000-07-09 15:48:49 +00001077PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001078{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001080 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001081
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001082 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001083#ifdef Py_USING_UNICODE
1084 /* The Unicode to string conversion is done here because the
1085 existing tp_setattro slots expect a string object as name
1086 and we wouldn't want to break those. */
1087 if (PyUnicode_Check(name)) {
1088 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1089 if (name == NULL)
1090 return -1;
1091 }
Tim Peters803526b2002-07-07 05:13:56 +00001092 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001093#endif
1094 {
1095 PyErr_SetString(PyExc_TypeError,
1096 "attribute name must be string");
1097 return -1;
1098 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001099 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001100 else
1101 Py_INCREF(name);
1102
1103 PyString_InternInPlace(&name);
1104 if (tp->tp_setattro != NULL) {
1105 err = (*tp->tp_setattro)(v, name, value);
1106 Py_DECREF(name);
1107 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001108 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001109 if (tp->tp_setattr != NULL) {
1110 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1111 Py_DECREF(name);
1112 return err;
1113 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001114 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1116 PyErr_Format(PyExc_TypeError,
1117 "'%.100s' object has no attributes "
1118 "(%s .%.100s)",
1119 tp->tp_name,
1120 value==NULL ? "del" : "assign to",
1121 PyString_AS_STRING(name));
1122 else
1123 PyErr_Format(PyExc_TypeError,
1124 "'%.100s' object has only read-only attributes "
1125 "(%s .%.100s)",
1126 tp->tp_name,
1127 value==NULL ? "del" : "assign to",
1128 PyString_AS_STRING(name));
1129 return -1;
1130}
1131
1132/* Helper to get a pointer to an object's __dict__ slot, if any */
1133
1134PyObject **
1135_PyObject_GetDictPtr(PyObject *obj)
1136{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001137 long dictoffset;
1138 PyTypeObject *tp = obj->ob_type;
1139
1140 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1141 return NULL;
1142 dictoffset = tp->tp_dictoffset;
1143 if (dictoffset == 0)
1144 return NULL;
1145 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001146 int tsize;
1147 size_t size;
1148
1149 tsize = ((PyVarObject *)obj)->ob_size;
1150 if (tsize < 0)
1151 tsize = -tsize;
1152 size = _PyObject_VAR_SIZE(tp, tsize);
1153
Tim Peters6d483d32001-10-06 21:27:34 +00001154 dictoffset += (long)size;
1155 assert(dictoffset > 0);
1156 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157 }
1158 return (PyObject **) ((char *)obj + dictoffset);
1159}
1160
1161/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1162
1163PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001164PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001165{
1166 Py_INCREF(obj);
1167 return obj;
1168}
1169
1170PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1172{
1173 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001174 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001175 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001177 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 PyObject **dictptr;
1179
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001180 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001181#ifdef Py_USING_UNICODE
1182 /* The Unicode to string conversion is done here because the
1183 existing tp_setattro slots expect a string object as name
1184 and we wouldn't want to break those. */
1185 if (PyUnicode_Check(name)) {
1186 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1187 if (name == NULL)
1188 return NULL;
1189 }
Tim Peters803526b2002-07-07 05:13:56 +00001190 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001191#endif
1192 {
1193 PyErr_SetString(PyExc_TypeError,
1194 "attribute name must be string");
1195 return NULL;
1196 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001197 }
1198 else
1199 Py_INCREF(name);
1200
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001202 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001203 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204 }
1205
Guido van Rossum056fbf42002-08-19 19:22:50 +00001206 /* Inline _PyType_Lookup */
1207 {
1208 int i, n;
1209 PyObject *mro, *base, *dict;
1210
1211 /* Look in tp_dict of types in MRO */
1212 mro = tp->tp_mro;
1213 assert(mro != NULL);
1214 assert(PyTuple_Check(mro));
1215 n = PyTuple_GET_SIZE(mro);
1216 for (i = 0; i < n; i++) {
1217 base = PyTuple_GET_ITEM(mro, i);
1218 if (PyClass_Check(base))
1219 dict = ((PyClassObject *)base)->cl_dict;
1220 else {
1221 assert(PyType_Check(base));
1222 dict = ((PyTypeObject *)base)->tp_dict;
1223 }
1224 assert(dict && PyDict_Check(dict));
1225 descr = PyDict_GetItem(dict, name);
1226 if (descr != NULL)
1227 break;
1228 }
1229 }
1230
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001231 Py_XINCREF(descr);
1232
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001234 if (descr != NULL &&
1235 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001237 if (f != NULL && PyDescr_IsData(descr)) {
1238 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001239 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001240 goto done;
1241 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 }
1243
Guido van Rossumc66ff442002-08-19 16:50:48 +00001244 /* Inline _PyObject_GetDictPtr */
1245 dictoffset = tp->tp_dictoffset;
1246 if (dictoffset != 0) {
1247 PyObject *dict;
1248 if (dictoffset < 0) {
1249 int tsize;
1250 size_t size;
1251
1252 tsize = ((PyVarObject *)obj)->ob_size;
1253 if (tsize < 0)
1254 tsize = -tsize;
1255 size = _PyObject_VAR_SIZE(tp, tsize);
1256
1257 dictoffset += (long)size;
1258 assert(dictoffset > 0);
1259 assert(dictoffset % SIZEOF_VOID_P == 0);
1260 }
1261 dictptr = (PyObject **) ((char *)obj + dictoffset);
1262 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001264 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 if (res != NULL) {
1266 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001267 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001268 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001269 }
1270 }
1271 }
1272
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001273 if (f != NULL) {
1274 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001275 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001276 goto done;
1277 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278
1279 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001280 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001281 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001282 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283 }
1284
1285 PyErr_Format(PyExc_AttributeError,
1286 "'%.50s' object has no attribute '%.400s'",
1287 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001288 done:
1289 Py_DECREF(name);
1290 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291}
1292
1293int
1294PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1295{
1296 PyTypeObject *tp = obj->ob_type;
1297 PyObject *descr;
1298 descrsetfunc f;
1299 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001300 int res = -1;
1301
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001302 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001303#ifdef Py_USING_UNICODE
1304 /* The Unicode to string conversion is done here because the
1305 existing tp_setattro slots expect a string object as name
1306 and we wouldn't want to break those. */
1307 if (PyUnicode_Check(name)) {
1308 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1309 if (name == NULL)
1310 return -1;
1311 }
Tim Peters803526b2002-07-07 05:13:56 +00001312 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001313#endif
1314 {
1315 PyErr_SetString(PyExc_TypeError,
1316 "attribute name must be string");
1317 return -1;
1318 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001319 }
1320 else
1321 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322
1323 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001324 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001325 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 }
1327
1328 descr = _PyType_Lookup(tp, name);
1329 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001330 if (descr != NULL &&
1331 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001333 if (f != NULL && PyDescr_IsData(descr)) {
1334 res = f(descr, obj, value);
1335 goto done;
1336 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001337 }
1338
1339 dictptr = _PyObject_GetDictPtr(obj);
1340 if (dictptr != NULL) {
1341 PyObject *dict = *dictptr;
1342 if (dict == NULL && value != NULL) {
1343 dict = PyDict_New();
1344 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001345 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001346 *dictptr = dict;
1347 }
1348 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 if (value == NULL)
1350 res = PyDict_DelItem(dict, name);
1351 else
1352 res = PyDict_SetItem(dict, name, value);
1353 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1354 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001355 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 }
1357 }
1358
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 if (f != NULL) {
1360 res = f(descr, obj, value);
1361 goto done;
1362 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363
1364 if (descr == NULL) {
1365 PyErr_Format(PyExc_AttributeError,
1366 "'%.50s' object has no attribute '%.400s'",
1367 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001368 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369 }
1370
1371 PyErr_Format(PyExc_AttributeError,
1372 "'%.50s' object attribute '%.400s' is read-only",
1373 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001374 done:
1375 Py_DECREF(name);
1376 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001377}
1378
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001379/* Test a value used as condition, e.g., in a for or if statement.
1380 Return -1 if an error occurred */
1381
1382int
Fred Drake100814d2000-07-09 15:48:49 +00001383PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001384{
1385 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001386 if (v == Py_True)
1387 return 1;
1388 if (v == Py_False)
1389 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001390 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001391 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001392 else if (v->ob_type->tp_as_number != NULL &&
1393 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001394 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001395 else if (v->ob_type->tp_as_mapping != NULL &&
1396 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001397 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001398 else if (v->ob_type->tp_as_sequence != NULL &&
1399 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001400 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1401 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001402 return 1;
1403 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001404}
1405
Tim Peters803526b2002-07-07 05:13:56 +00001406/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001407 Return -1 if an error occurred */
1408
1409int
Fred Drake100814d2000-07-09 15:48:49 +00001410PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001411{
1412 int res;
1413 res = PyObject_IsTrue(v);
1414 if (res < 0)
1415 return res;
1416 return res == 0;
1417}
1418
Guido van Rossum5524a591995-01-10 15:26:20 +00001419/* Coerce two numeric types to the "larger" one.
1420 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001421 Return value:
1422 -1 if an error occurred;
1423 0 if the coercion succeeded (and then the reference counts are increased);
1424 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001425*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001426int
Fred Drake100814d2000-07-09 15:48:49 +00001427PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001428{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429 register PyObject *v = *pv;
1430 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001431 int res;
1432
Guido van Rossum517c7d42002-04-26 02:49:14 +00001433 /* Shortcut only for old-style types */
1434 if (v->ob_type == w->ob_type &&
1435 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1436 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001437 Py_INCREF(v);
1438 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001439 return 0;
1440 }
1441 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1442 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1443 if (res <= 0)
1444 return res;
1445 }
1446 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1447 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1448 if (res <= 0)
1449 return res;
1450 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001451 return 1;
1452}
1453
Guido van Rossume797ec12001-01-17 15:24:28 +00001454/* Coerce two numeric types to the "larger" one.
1455 Increment the reference count on each argument.
1456 Return -1 and raise an exception if no coercion is possible
1457 (and then no reference count is incremented).
1458*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001459int
Fred Drake100814d2000-07-09 15:48:49 +00001460PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001461{
1462 int err = PyNumber_CoerceEx(pv, pw);
1463 if (err <= 0)
1464 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001465 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001466 return -1;
1467}
1468
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001469
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001470/* Test whether an object can be called */
1471
1472int
Fred Drake100814d2000-07-09 15:48:49 +00001473PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001474{
1475 if (x == NULL)
1476 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001477 if (PyInstance_Check(x)) {
1478 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001479 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001480 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001481 return 0;
1482 }
1483 /* Could test recursively but don't, for fear of endless
1484 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001485 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001486 return 1;
1487 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001488 else {
1489 return x->ob_type->tp_call != NULL;
1490 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001491}
1492
Tim Peters7eea37e2001-09-04 22:08:56 +00001493/* Helper for PyObject_Dir.
1494 Merge the __dict__ of aclass into dict, and recursively also all
1495 the __dict__s of aclass's base classes. The order of merging isn't
1496 defined, as it's expected that only the final set of dict keys is
1497 interesting.
1498 Return 0 on success, -1 on error.
1499*/
1500
1501static int
1502merge_class_dict(PyObject* dict, PyObject* aclass)
1503{
1504 PyObject *classdict;
1505 PyObject *bases;
1506
1507 assert(PyDict_Check(dict));
1508 assert(aclass);
1509
1510 /* Merge in the type's dict (if any). */
1511 classdict = PyObject_GetAttrString(aclass, "__dict__");
1512 if (classdict == NULL)
1513 PyErr_Clear();
1514 else {
1515 int status = PyDict_Update(dict, classdict);
1516 Py_DECREF(classdict);
1517 if (status < 0)
1518 return -1;
1519 }
1520
1521 /* Recursively merge in the base types' (if any) dicts. */
1522 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001523 if (bases == NULL)
1524 PyErr_Clear();
1525 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001526 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001527 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001528 n = PySequence_Size(bases); /* This better be right */
1529 if (n < 0)
1530 PyErr_Clear();
1531 else {
1532 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001533 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001534 PyObject *base = PySequence_GetItem(bases, i);
1535 if (base == NULL) {
1536 Py_DECREF(bases);
1537 return -1;
1538 }
Tim Peters18e70832003-02-05 19:35:19 +00001539 status = merge_class_dict(dict, base);
1540 Py_DECREF(base);
1541 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001542 Py_DECREF(bases);
1543 return -1;
1544 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001545 }
1546 }
1547 Py_DECREF(bases);
1548 }
1549 return 0;
1550}
1551
Tim Peters305b5852001-09-17 02:38:46 +00001552/* Helper for PyObject_Dir.
1553 If obj has an attr named attrname that's a list, merge its string
1554 elements into keys of dict.
1555 Return 0 on success, -1 on error. Errors due to not finding the attr,
1556 or the attr not being a list, are suppressed.
1557*/
1558
1559static int
1560merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1561{
1562 PyObject *list;
1563 int result = 0;
1564
1565 assert(PyDict_Check(dict));
1566 assert(obj);
1567 assert(attrname);
1568
1569 list = PyObject_GetAttrString(obj, attrname);
1570 if (list == NULL)
1571 PyErr_Clear();
1572
1573 else if (PyList_Check(list)) {
1574 int i;
1575 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1576 PyObject *item = PyList_GET_ITEM(list, i);
1577 if (PyString_Check(item)) {
1578 result = PyDict_SetItem(dict, item, Py_None);
1579 if (result < 0)
1580 break;
1581 }
1582 }
1583 }
1584
1585 Py_XDECREF(list);
1586 return result;
1587}
1588
Tim Peters7eea37e2001-09-04 22:08:56 +00001589/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1590 docstring, which should be kept in synch with this implementation. */
1591
1592PyObject *
1593PyObject_Dir(PyObject *arg)
1594{
1595 /* Set exactly one of these non-NULL before the end. */
1596 PyObject *result = NULL; /* result list */
1597 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1598
1599 /* If NULL arg, return the locals. */
1600 if (arg == NULL) {
1601 PyObject *locals = PyEval_GetLocals();
1602 if (locals == NULL)
1603 goto error;
1604 result = PyDict_Keys(locals);
1605 if (result == NULL)
1606 goto error;
1607 }
1608
1609 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001610 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001611 masterdict = PyObject_GetAttrString(arg, "__dict__");
1612 if (masterdict == NULL)
1613 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001614 if (!PyDict_Check(masterdict)) {
1615 PyErr_SetString(PyExc_TypeError,
1616 "module.__dict__ is not a dictionary");
1617 goto error;
1618 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001619 }
1620
1621 /* Elif some form of type or class, grab its dict and its bases.
1622 We deliberately don't suck up its __class__, as methods belonging
1623 to the metaclass would probably be more confusing than helpful. */
1624 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1625 masterdict = PyDict_New();
1626 if (masterdict == NULL)
1627 goto error;
1628 if (merge_class_dict(masterdict, arg) < 0)
1629 goto error;
1630 }
1631
1632 /* Else look at its dict, and the attrs reachable from its class. */
1633 else {
1634 PyObject *itsclass;
1635 /* Create a dict to start with. CAUTION: Not everything
1636 responding to __dict__ returns a dict! */
1637 masterdict = PyObject_GetAttrString(arg, "__dict__");
1638 if (masterdict == NULL) {
1639 PyErr_Clear();
1640 masterdict = PyDict_New();
1641 }
1642 else if (!PyDict_Check(masterdict)) {
1643 Py_DECREF(masterdict);
1644 masterdict = PyDict_New();
1645 }
1646 else {
1647 /* The object may have returned a reference to its
1648 dict, so copy it to avoid mutating it. */
1649 PyObject *temp = PyDict_Copy(masterdict);
1650 Py_DECREF(masterdict);
1651 masterdict = temp;
1652 }
1653 if (masterdict == NULL)
1654 goto error;
1655
Tim Peters305b5852001-09-17 02:38:46 +00001656 /* Merge in __members__ and __methods__ (if any).
1657 XXX Would like this to go away someday; for now, it's
1658 XXX needed to get at im_self etc of method objects. */
1659 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1660 goto error;
1661 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1662 goto error;
1663
Tim Peters7eea37e2001-09-04 22:08:56 +00001664 /* Merge in attrs reachable from its class.
1665 CAUTION: Not all objects have a __class__ attr. */
1666 itsclass = PyObject_GetAttrString(arg, "__class__");
1667 if (itsclass == NULL)
1668 PyErr_Clear();
1669 else {
1670 int status = merge_class_dict(masterdict, itsclass);
1671 Py_DECREF(itsclass);
1672 if (status < 0)
1673 goto error;
1674 }
1675 }
1676
1677 assert((result == NULL) ^ (masterdict == NULL));
1678 if (masterdict != NULL) {
1679 /* The result comes from its keys. */
1680 assert(result == NULL);
1681 result = PyDict_Keys(masterdict);
1682 if (result == NULL)
1683 goto error;
1684 }
1685
1686 assert(result);
1687 if (PyList_Sort(result) != 0)
1688 goto error;
1689 else
1690 goto normal_return;
1691
1692 error:
1693 Py_XDECREF(result);
1694 result = NULL;
1695 /* fall through */
1696 normal_return:
1697 Py_XDECREF(masterdict);
1698 return result;
1699}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001700
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001701/*
1702NoObject is usable as a non-NULL undefined value, used by the macro None.
1703There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001704so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001705(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001706*/
1707
Guido van Rossum0c182a11992-03-27 17:26:13 +00001708/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001709static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001710none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001711{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001712 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001713}
1714
Barry Warsaw9bf16442001-01-23 16:24:35 +00001715/* ARGUSED */
1716static void
Tim Peters803526b2002-07-07 05:13:56 +00001717none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001718{
1719 /* This should never get called, but we also don't want to SEGV if
1720 * we accidently decref None out of existance.
1721 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001722 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001723}
1724
1725
Guido van Rossumba21a492001-08-16 08:17:26 +00001726static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001727 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001728 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001729 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001730 0,
1731 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001732 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001733 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001734 0, /*tp_getattr*/
1735 0, /*tp_setattr*/
1736 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001737 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001738 0, /*tp_as_number*/
1739 0, /*tp_as_sequence*/
1740 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001741 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001742};
1743
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001744PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001745 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001746};
1747
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001748/* NotImplemented is an object that can be used to signal that an
1749 operation is not implemented for the given type combination. */
1750
1751static PyObject *
1752NotImplemented_repr(PyObject *op)
1753{
1754 return PyString_FromString("NotImplemented");
1755}
1756
1757static PyTypeObject PyNotImplemented_Type = {
1758 PyObject_HEAD_INIT(&PyType_Type)
1759 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001760 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001761 0,
1762 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001763 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001764 0, /*tp_print*/
1765 0, /*tp_getattr*/
1766 0, /*tp_setattr*/
1767 0, /*tp_compare*/
1768 (reprfunc)NotImplemented_repr, /*tp_repr*/
1769 0, /*tp_as_number*/
1770 0, /*tp_as_sequence*/
1771 0, /*tp_as_mapping*/
1772 0, /*tp_hash */
1773};
1774
1775PyObject _Py_NotImplementedStruct = {
1776 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1777};
1778
Guido van Rossumba21a492001-08-16 08:17:26 +00001779void
1780_Py_ReadyTypes(void)
1781{
1782 if (PyType_Ready(&PyType_Type) < 0)
1783 Py_FatalError("Can't initialize 'type'");
1784
Guido van Rossum77f6a652002-04-03 22:41:51 +00001785 if (PyType_Ready(&PyBool_Type) < 0)
1786 Py_FatalError("Can't initialize 'bool'");
1787
Guido van Rossumcacfc072002-05-24 19:01:59 +00001788 if (PyType_Ready(&PyString_Type) < 0)
1789 Py_FatalError("Can't initialize 'str'");
1790
Guido van Rossumba21a492001-08-16 08:17:26 +00001791 if (PyType_Ready(&PyList_Type) < 0)
1792 Py_FatalError("Can't initialize 'list'");
1793
1794 if (PyType_Ready(&PyNone_Type) < 0)
1795 Py_FatalError("Can't initialize type(None)");
1796
1797 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1798 Py_FatalError("Can't initialize type(NotImplemented)");
1799}
1800
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001801
Guido van Rossum84a90321996-05-22 16:34:47 +00001802#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001803
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001804void
Fred Drake100814d2000-07-09 15:48:49 +00001805_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001806{
Tim Peters34592512002-07-11 06:23:50 +00001807 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001808 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001809 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001810 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001811}
1812
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001813void
Fred Drake100814d2000-07-09 15:48:49 +00001814_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001815{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001816#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001817 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001818#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001819 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001820 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001821 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001822 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001823 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001824#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001825 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1826 if (p == op)
1827 break;
1828 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001829 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001830 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001831#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001832 op->_ob_next->_ob_prev = op->_ob_prev;
1833 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001834 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001835 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001836}
1837
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001838void
Fred Drake100814d2000-07-09 15:48:49 +00001839_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001840{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001841 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001842 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001843 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844}
1845
Tim Peters269b2a62003-04-17 19:52:29 +00001846/* Print all live objects. Because PyObject_Print is called, the
1847 * interpreter must be in a healthy state.
1848 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001849void
Fred Drake100814d2000-07-09 15:48:49 +00001850_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001853 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001855 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001856 if (PyObject_Print(op, fp, 0) != 0)
1857 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858 putc('\n', fp);
1859 }
1860}
1861
Tim Peters269b2a62003-04-17 19:52:29 +00001862/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1863 * doesn't make any calls to the Python C API, so is always safe to call.
1864 */
1865void
1866_Py_PrintReferenceAddresses(FILE *fp)
1867{
1868 PyObject *op;
1869 fprintf(fp, "Remaining object addresses:\n");
1870 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001871 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1872 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001873}
1874
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001875PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001876_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001877{
1878 int i, n;
1879 PyObject *t = NULL;
1880 PyObject *res, *op;
1881
1882 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1883 return NULL;
1884 op = refchain._ob_next;
1885 res = PyList_New(0);
1886 if (res == NULL)
1887 return NULL;
1888 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1889 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001890 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001891 op = op->_ob_next;
1892 if (op == &refchain)
1893 return res;
1894 }
1895 if (PyList_Append(res, op) < 0) {
1896 Py_DECREF(res);
1897 return NULL;
1898 }
1899 op = op->_ob_next;
1900 }
1901 return res;
1902}
1903
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001904#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001905
1906
1907/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001908PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001909
1910
1911/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001912int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001913
1914
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001915/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001916
Thomas Wouters334fb892000-07-25 12:56:38 +00001917void *
Fred Drake100814d2000-07-09 15:48:49 +00001918PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001919{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001920 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001921}
1922
Thomas Wouters334fb892000-07-25 12:56:38 +00001923void *
1924PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001925{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001926 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001927}
1928
1929void
Thomas Wouters334fb892000-07-25 12:56:38 +00001930PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001931{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001932 PyMem_FREE(p);
1933}
1934
1935
Guido van Rossum86610361998-04-10 22:32:46 +00001936/* These methods are used to control infinite recursion in repr, str, print,
1937 etc. Container objects that may recursively contain themselves,
1938 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1939 Py_ReprLeave() to avoid infinite recursion.
1940
1941 Py_ReprEnter() returns 0 the first time it is called for a particular
1942 object and 1 every time thereafter. It returns -1 if an exception
1943 occurred. Py_ReprLeave() has no return value.
1944
1945 See dictobject.c and listobject.c for examples of use.
1946*/
1947
1948#define KEY "Py_Repr"
1949
1950int
Fred Drake100814d2000-07-09 15:48:49 +00001951Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001952{
1953 PyObject *dict;
1954 PyObject *list;
1955 int i;
1956
1957 dict = PyThreadState_GetDict();
1958 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001959 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001960 list = PyDict_GetItemString(dict, KEY);
1961 if (list == NULL) {
1962 list = PyList_New(0);
1963 if (list == NULL)
1964 return -1;
1965 if (PyDict_SetItemString(dict, KEY, list) < 0)
1966 return -1;
1967 Py_DECREF(list);
1968 }
1969 i = PyList_GET_SIZE(list);
1970 while (--i >= 0) {
1971 if (PyList_GET_ITEM(list, i) == obj)
1972 return 1;
1973 }
1974 PyList_Append(list, obj);
1975 return 0;
1976}
1977
1978void
Fred Drake100814d2000-07-09 15:48:49 +00001979Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001980{
1981 PyObject *dict;
1982 PyObject *list;
1983 int i;
1984
1985 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001986 if (dict == NULL)
1987 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001988 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001989 if (list == NULL || !PyList_Check(list))
1990 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001991 i = PyList_GET_SIZE(list);
1992 /* Count backwards because we always expect obj to be list[-1] */
1993 while (--i >= 0) {
1994 if (PyList_GET_ITEM(list, i) == obj) {
1995 PyList_SetSlice(list, i, i + 1, NULL);
1996 break;
1997 }
1998 }
1999}
Guido van Rossumd724b232000-03-13 16:01:29 +00002000
Tim Peters803526b2002-07-07 05:13:56 +00002001/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002002
Tim Peters803526b2002-07-07 05:13:56 +00002003/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002004int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002005
Tim Peters803526b2002-07-07 05:13:56 +00002006/* List of objects that still need to be cleaned up, singly linked via their
2007 * gc headers' gc_prev pointers.
2008 */
2009PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002010
Tim Peters803526b2002-07-07 05:13:56 +00002011/* Add op to the _PyTrash_delete_later list. Called when the current
2012 * call-stack depth gets large. op must be a currently untracked gc'ed
2013 * object, with refcount 0. Py_DECREF must already have been called on it.
2014 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002015void
Fred Drake100814d2000-07-09 15:48:49 +00002016_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002017{
Tim Peters803526b2002-07-07 05:13:56 +00002018 assert(PyObject_IS_GC(op));
2019 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2020 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002021 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002022 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002023}
2024
Tim Peters803526b2002-07-07 05:13:56 +00002025/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2026 * the call-stack unwinds again.
2027 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002028void
Fred Drake100814d2000-07-09 15:48:49 +00002029_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002030{
2031 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002032 PyObject *op = _PyTrash_delete_later;
2033 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002034
Neil Schemenauerf589c052002-03-29 03:05:54 +00002035 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002036 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002037
Tim Peters803526b2002-07-07 05:13:56 +00002038 /* Call the deallocator directly. This used to try to
2039 * fool Py_DECREF into calling it indirectly, but
2040 * Py_DECREF was already called on this object, and in
2041 * assorted non-release builds calling Py_DECREF again ends
2042 * up distorting allocation statistics.
2043 */
2044 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002045 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002046 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002047 --_PyTrash_delete_nesting;
2048 }
2049}