blob: b913a064dfecdb822bd65830454c7d490ac11a7c [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{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000749 int result;
750
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000751 if (v == NULL || w == NULL) {
752 PyErr_BadInternalCall();
753 return -1;
754 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755 if (v == w)
756 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000757 if (Py_EnterRecursiveCall(" in cmp"))
758 return -1;
759 result = do_cmp(v, w);
760 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000761 return result < 0 ? -1 : result;
762}
763
Tim Petersc99213f2001-11-04 05:57:16 +0000764/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000765static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000766convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000767{
Guido van Rossume797ec12001-01-17 15:24:28 +0000768 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000769 switch (op) {
770 case Py_LT: c = c < 0; break;
771 case Py_LE: c = c <= 0; break;
772 case Py_EQ: c = c == 0; break;
773 case Py_NE: c = c != 0; break;
774 case Py_GT: c = c > 0; break;
775 case Py_GE: c = c >= 0; break;
776 }
777 result = c ? Py_True : Py_False;
778 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000779 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780}
Tim Peters803526b2002-07-07 05:13:56 +0000781
Tim Petersc99213f2001-11-04 05:57:16 +0000782/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
783 Return
784 NULL if error
785 Py_True if v op w
786 Py_False if not (v op w)
787*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000788static PyObject *
789try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
790{
791 int c;
792
793 c = try_3way_compare(v, w);
794 if (c >= 2)
795 c = default_3way_compare(v, w);
796 if (c <= -2)
797 return NULL;
798 return convert_3way_to_object(op, c);
799}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800
Tim Petersc99213f2001-11-04 05:57:16 +0000801/* Do rich comparison on v and w. Return
802 NULL if error
803 Else a new reference to an object other than Py_NotImplemented, usually(?):
804 Py_True if v op w
805 Py_False if not (v op w)
806*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000807static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000808do_richcmp(PyObject *v, PyObject *w, int op)
809{
810 PyObject *res;
811
812 res = try_rich_compare(v, w, op);
813 if (res != Py_NotImplemented)
814 return res;
815 Py_DECREF(res);
816
817 return try_3way_to_rich_compare(v, w, op);
818}
819
Tim Petersc99213f2001-11-04 05:57:16 +0000820/* Return:
821 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000822 some object not equal to NotImplemented if it is implemented
823 (this latter object may not be a Boolean).
824*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000825PyObject *
826PyObject_RichCompare(PyObject *v, PyObject *w, int op)
827{
828 PyObject *res;
829
830 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000831 if (Py_EnterRecursiveCall(" in cmp"))
832 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000833
Armin Rigo2b3eb402003-10-28 12:05:48 +0000834 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000835 get out cheap (don't bother with coercions etc.). */
836 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
837 cmpfunc fcmp;
838 richcmpfunc frich = RICHCOMPARE(v->ob_type);
839 /* If the type has richcmp, try it first. try_rich_compare
840 tries it two-sided, which is not needed since we've a
841 single type only. */
842 if (frich != NULL) {
843 res = (*frich)(v, w, op);
844 if (res != Py_NotImplemented)
845 goto Done;
846 Py_DECREF(res);
847 }
848 /* No richcmp, or this particular richmp not implemented.
849 Try 3-way cmp. */
850 fcmp = v->ob_type->tp_compare;
851 if (fcmp != NULL) {
852 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000853 c = adjust_tp_compare(c);
854 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000855 res = NULL;
856 goto Done;
857 }
858 res = convert_3way_to_object(op, c);
859 goto Done;
860 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000861 }
Tim Peters67754e92001-11-04 07:29:31 +0000862
863 /* Fast path not taken, or couldn't deliver a useful result. */
864 res = do_richcmp(v, w, op);
865Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000866 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000867 return res;
868}
869
Tim Petersde9725f2001-05-05 10:06:17 +0000870/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000871int
872PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
873{
874 PyObject *res = PyObject_RichCompare(v, w, op);
875 int ok;
876
877 if (res == NULL)
878 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000879 if (PyBool_Check(res))
880 ok = (res == Py_True);
881 else
882 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000883 Py_DECREF(res);
884 return ok;
885}
Fred Drake13634cf2000-06-29 19:17:04 +0000886
887/* Set of hash utility functions to help maintaining the invariant that
888 iff a==b then hash(a)==hash(b)
889
890 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
891*/
892
893long
Fred Drake100814d2000-07-09 15:48:49 +0000894_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000895{
Tim Peters39dce292000-08-15 03:34:48 +0000896 double intpart, fractpart;
897 int expo;
898 long hipart;
899 long x; /* the final hash value */
900 /* This is designed so that Python numbers of different types
901 * that compare equal hash to the same value; otherwise comparisons
902 * of mapping keys will turn out weird.
903 */
904
Tim Peters39dce292000-08-15 03:34:48 +0000905 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000906 if (fractpart == 0.0) {
907 /* This must return the same hash as an equal int or long. */
908 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
909 /* Convert to long and use its hash. */
910 PyObject *plong; /* converted to Python long */
911 if (Py_IS_INFINITY(intpart))
912 /* can't convert to long int -- arbitrary */
913 v = v < 0 ? -271828.0 : 314159.0;
914 plong = PyLong_FromDouble(v);
915 if (plong == NULL)
916 return -1;
917 x = PyObject_Hash(plong);
918 Py_DECREF(plong);
919 return x;
920 }
921 /* Fits in a C long == a Python int, so is its own hash. */
922 x = (long)intpart;
923 if (x == -1)
924 x = -2;
925 return x;
926 }
927 /* The fractional part is non-zero, so we don't have to worry about
928 * making this match the hash of some other type.
929 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000930 * Since the VAX D double format has 56 mantissa bits, which is the
931 * most of any double format in use, each of these parts may have as
932 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000933 * So, assuming sizeof(long) >= 4, each part can be broken into two
934 * longs; frexp and multiplication are used to do that.
935 * Also, since the Cray double format has 15 exponent bits, which is
936 * the most of any double format in use, shifting the exponent field
937 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000938 */
Tim Peters39dce292000-08-15 03:34:48 +0000939 v = frexp(v, &expo);
940 v *= 2147483648.0; /* 2**31 */
941 hipart = (long)v; /* take the top 32 bits */
942 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
943 x = hipart + (long)v + (expo << 15);
944 if (x == -1)
945 x = -2;
946 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000947}
948
949long
Fred Drake100814d2000-07-09 15:48:49 +0000950_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000951{
952#if SIZEOF_LONG >= SIZEOF_VOID_P
953 return (long)p;
954#else
955 /* convert to a Python long and hash that */
956 PyObject* longobj;
957 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000958
Fred Drake13634cf2000-06-29 19:17:04 +0000959 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
960 x = -1;
961 goto finally;
962 }
963 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000964
Fred Drake13634cf2000-06-29 19:17:04 +0000965finally:
966 Py_XDECREF(longobj);
967 return x;
968#endif
969}
970
971
Guido van Rossum9bfef441993-03-29 10:43:31 +0000972long
Fred Drake100814d2000-07-09 15:48:49 +0000973PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000974{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000975 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000976 if (tp->tp_hash != NULL)
977 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000978 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000979 return _Py_HashPointer(v); /* Use address as hash value */
980 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000981 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000982 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000983 return -1;
984}
985
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000986PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000987PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000988{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000990
Tim Peters6d6c1a32001-08-02 04:15:00 +0000991 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000992 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 w = PyString_InternFromString(name);
994 if (w == NULL)
995 return NULL;
996 res = PyObject_GetAttr(v, w);
997 Py_XDECREF(w);
998 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000999}
1000
1001int
Fred Drake100814d2000-07-09 15:48:49 +00001002PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001003{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001004 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001005 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001006 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001007 return 1;
1008 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001009 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001010 return 0;
1011}
1012
1013int
Fred Drake100814d2000-07-09 15:48:49 +00001014PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001015{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016 PyObject *s;
1017 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001018
Tim Peters6d6c1a32001-08-02 04:15:00 +00001019 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001020 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001021 s = PyString_InternFromString(name);
1022 if (s == NULL)
1023 return -1;
1024 res = PyObject_SetAttr(v, s, w);
1025 Py_XDECREF(s);
1026 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001027}
1028
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001029PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001030PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001031{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032 PyTypeObject *tp = v->ob_type;
1033
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001034 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001035#ifdef Py_USING_UNICODE
1036 /* The Unicode to string conversion is done here because the
1037 existing tp_getattro slots expect a string object as name
1038 and we wouldn't want to break those. */
1039 if (PyUnicode_Check(name)) {
1040 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1041 if (name == NULL)
1042 return NULL;
1043 }
1044 else
1045#endif
1046 {
1047 PyErr_SetString(PyExc_TypeError,
1048 "attribute name must be string");
1049 return NULL;
1050 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001051 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052 if (tp->tp_getattro != NULL)
1053 return (*tp->tp_getattro)(v, name);
1054 if (tp->tp_getattr != NULL)
1055 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1056 PyErr_Format(PyExc_AttributeError,
1057 "'%.50s' object has no attribute '%.400s'",
1058 tp->tp_name, PyString_AS_STRING(name));
1059 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001060}
1061
1062int
Fred Drake100814d2000-07-09 15:48:49 +00001063PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001064{
1065 PyObject *res = PyObject_GetAttr(v, name);
1066 if (res != NULL) {
1067 Py_DECREF(res);
1068 return 1;
1069 }
1070 PyErr_Clear();
1071 return 0;
1072}
1073
1074int
Fred Drake100814d2000-07-09 15:48:49 +00001075PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001076{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001078 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001079
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001080 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001081#ifdef Py_USING_UNICODE
1082 /* The Unicode to string conversion is done here because the
1083 existing tp_setattro slots expect a string object as name
1084 and we wouldn't want to break those. */
1085 if (PyUnicode_Check(name)) {
1086 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1087 if (name == NULL)
1088 return -1;
1089 }
Tim Peters803526b2002-07-07 05:13:56 +00001090 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001091#endif
1092 {
1093 PyErr_SetString(PyExc_TypeError,
1094 "attribute name must be string");
1095 return -1;
1096 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098 else
1099 Py_INCREF(name);
1100
1101 PyString_InternInPlace(&name);
1102 if (tp->tp_setattro != NULL) {
1103 err = (*tp->tp_setattro)(v, name, value);
1104 Py_DECREF(name);
1105 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001106 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 if (tp->tp_setattr != NULL) {
1108 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1109 Py_DECREF(name);
1110 return err;
1111 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001112 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1114 PyErr_Format(PyExc_TypeError,
1115 "'%.100s' object has no attributes "
1116 "(%s .%.100s)",
1117 tp->tp_name,
1118 value==NULL ? "del" : "assign to",
1119 PyString_AS_STRING(name));
1120 else
1121 PyErr_Format(PyExc_TypeError,
1122 "'%.100s' object has only read-only attributes "
1123 "(%s .%.100s)",
1124 tp->tp_name,
1125 value==NULL ? "del" : "assign to",
1126 PyString_AS_STRING(name));
1127 return -1;
1128}
1129
1130/* Helper to get a pointer to an object's __dict__ slot, if any */
1131
1132PyObject **
1133_PyObject_GetDictPtr(PyObject *obj)
1134{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 long dictoffset;
1136 PyTypeObject *tp = obj->ob_type;
1137
1138 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1139 return NULL;
1140 dictoffset = tp->tp_dictoffset;
1141 if (dictoffset == 0)
1142 return NULL;
1143 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001144 int tsize;
1145 size_t size;
1146
1147 tsize = ((PyVarObject *)obj)->ob_size;
1148 if (tsize < 0)
1149 tsize = -tsize;
1150 size = _PyObject_VAR_SIZE(tp, tsize);
1151
Tim Peters6d483d32001-10-06 21:27:34 +00001152 dictoffset += (long)size;
1153 assert(dictoffset > 0);
1154 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 }
1156 return (PyObject **) ((char *)obj + dictoffset);
1157}
1158
1159/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1160
1161PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001162PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001163{
1164 Py_INCREF(obj);
1165 return obj;
1166}
1167
1168PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1170{
1171 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001172 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001173 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001175 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 PyObject **dictptr;
1177
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001178 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001179#ifdef Py_USING_UNICODE
1180 /* The Unicode to string conversion is done here because the
1181 existing tp_setattro slots expect a string object as name
1182 and we wouldn't want to break those. */
1183 if (PyUnicode_Check(name)) {
1184 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1185 if (name == NULL)
1186 return NULL;
1187 }
Tim Peters803526b2002-07-07 05:13:56 +00001188 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001189#endif
1190 {
1191 PyErr_SetString(PyExc_TypeError,
1192 "attribute name must be string");
1193 return NULL;
1194 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001195 }
1196 else
1197 Py_INCREF(name);
1198
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001200 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001201 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 }
1203
Guido van Rossum056fbf42002-08-19 19:22:50 +00001204 /* Inline _PyType_Lookup */
1205 {
1206 int i, n;
1207 PyObject *mro, *base, *dict;
1208
1209 /* Look in tp_dict of types in MRO */
1210 mro = tp->tp_mro;
1211 assert(mro != NULL);
1212 assert(PyTuple_Check(mro));
1213 n = PyTuple_GET_SIZE(mro);
1214 for (i = 0; i < n; i++) {
1215 base = PyTuple_GET_ITEM(mro, i);
1216 if (PyClass_Check(base))
1217 dict = ((PyClassObject *)base)->cl_dict;
1218 else {
1219 assert(PyType_Check(base));
1220 dict = ((PyTypeObject *)base)->tp_dict;
1221 }
1222 assert(dict && PyDict_Check(dict));
1223 descr = PyDict_GetItem(dict, name);
1224 if (descr != NULL)
1225 break;
1226 }
1227 }
1228
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001229 Py_XINCREF(descr);
1230
Tim Peters6d6c1a32001-08-02 04:15:00 +00001231 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001232 if (descr != NULL &&
1233 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001235 if (f != NULL && PyDescr_IsData(descr)) {
1236 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001237 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001238 goto done;
1239 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 }
1241
Guido van Rossumc66ff442002-08-19 16:50:48 +00001242 /* Inline _PyObject_GetDictPtr */
1243 dictoffset = tp->tp_dictoffset;
1244 if (dictoffset != 0) {
1245 PyObject *dict;
1246 if (dictoffset < 0) {
1247 int tsize;
1248 size_t size;
1249
1250 tsize = ((PyVarObject *)obj)->ob_size;
1251 if (tsize < 0)
1252 tsize = -tsize;
1253 size = _PyObject_VAR_SIZE(tp, tsize);
1254
1255 dictoffset += (long)size;
1256 assert(dictoffset > 0);
1257 assert(dictoffset % SIZEOF_VOID_P == 0);
1258 }
1259 dictptr = (PyObject **) ((char *)obj + dictoffset);
1260 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001261 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001262 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 if (res != NULL) {
1264 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001265 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001266 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267 }
1268 }
1269 }
1270
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001271 if (f != NULL) {
1272 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001273 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001274 goto done;
1275 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276
1277 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001278 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001279 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001280 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281 }
1282
1283 PyErr_Format(PyExc_AttributeError,
1284 "'%.50s' object has no attribute '%.400s'",
1285 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001286 done:
1287 Py_DECREF(name);
1288 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289}
1290
1291int
1292PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1293{
1294 PyTypeObject *tp = obj->ob_type;
1295 PyObject *descr;
1296 descrsetfunc f;
1297 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001298 int res = -1;
1299
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001300 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001301#ifdef Py_USING_UNICODE
1302 /* The Unicode to string conversion is done here because the
1303 existing tp_setattro slots expect a string object as name
1304 and we wouldn't want to break those. */
1305 if (PyUnicode_Check(name)) {
1306 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1307 if (name == NULL)
1308 return -1;
1309 }
Tim Peters803526b2002-07-07 05:13:56 +00001310 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001311#endif
1312 {
1313 PyErr_SetString(PyExc_TypeError,
1314 "attribute name must be string");
1315 return -1;
1316 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001317 }
1318 else
1319 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320
1321 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001322 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001323 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001324 }
1325
1326 descr = _PyType_Lookup(tp, name);
1327 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001328 if (descr != NULL &&
1329 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001331 if (f != NULL && PyDescr_IsData(descr)) {
1332 res = f(descr, obj, value);
1333 goto done;
1334 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335 }
1336
1337 dictptr = _PyObject_GetDictPtr(obj);
1338 if (dictptr != NULL) {
1339 PyObject *dict = *dictptr;
1340 if (dict == NULL && value != NULL) {
1341 dict = PyDict_New();
1342 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001343 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344 *dictptr = dict;
1345 }
1346 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347 if (value == NULL)
1348 res = PyDict_DelItem(dict, name);
1349 else
1350 res = PyDict_SetItem(dict, name, value);
1351 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1352 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001353 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354 }
1355 }
1356
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001357 if (f != NULL) {
1358 res = f(descr, obj, value);
1359 goto done;
1360 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001361
1362 if (descr == NULL) {
1363 PyErr_Format(PyExc_AttributeError,
1364 "'%.50s' object has no attribute '%.400s'",
1365 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001366 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367 }
1368
1369 PyErr_Format(PyExc_AttributeError,
1370 "'%.50s' object attribute '%.400s' is read-only",
1371 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001372 done:
1373 Py_DECREF(name);
1374 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001375}
1376
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001377/* Test a value used as condition, e.g., in a for or if statement.
1378 Return -1 if an error occurred */
1379
1380int
Fred Drake100814d2000-07-09 15:48:49 +00001381PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001382{
1383 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001384 if (v == Py_True)
1385 return 1;
1386 if (v == Py_False)
1387 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001389 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001390 else if (v->ob_type->tp_as_number != NULL &&
1391 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001392 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001393 else if (v->ob_type->tp_as_mapping != NULL &&
1394 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001395 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001396 else if (v->ob_type->tp_as_sequence != NULL &&
1397 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001398 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1399 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001400 return 1;
1401 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001402}
1403
Tim Peters803526b2002-07-07 05:13:56 +00001404/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001405 Return -1 if an error occurred */
1406
1407int
Fred Drake100814d2000-07-09 15:48:49 +00001408PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001409{
1410 int res;
1411 res = PyObject_IsTrue(v);
1412 if (res < 0)
1413 return res;
1414 return res == 0;
1415}
1416
Guido van Rossum5524a591995-01-10 15:26:20 +00001417/* Coerce two numeric types to the "larger" one.
1418 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001419 Return value:
1420 -1 if an error occurred;
1421 0 if the coercion succeeded (and then the reference counts are increased);
1422 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001423*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001424int
Fred Drake100814d2000-07-09 15:48:49 +00001425PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001426{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001427 register PyObject *v = *pv;
1428 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001429 int res;
1430
Guido van Rossum517c7d42002-04-26 02:49:14 +00001431 /* Shortcut only for old-style types */
1432 if (v->ob_type == w->ob_type &&
1433 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1434 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001435 Py_INCREF(v);
1436 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001437 return 0;
1438 }
1439 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1440 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1441 if (res <= 0)
1442 return res;
1443 }
1444 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1445 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1446 if (res <= 0)
1447 return res;
1448 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001449 return 1;
1450}
1451
Guido van Rossume797ec12001-01-17 15:24:28 +00001452/* Coerce two numeric types to the "larger" one.
1453 Increment the reference count on each argument.
1454 Return -1 and raise an exception if no coercion is possible
1455 (and then no reference count is incremented).
1456*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001457int
Fred Drake100814d2000-07-09 15:48:49 +00001458PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001459{
1460 int err = PyNumber_CoerceEx(pv, pw);
1461 if (err <= 0)
1462 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001463 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001464 return -1;
1465}
1466
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001467
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001468/* Test whether an object can be called */
1469
1470int
Fred Drake100814d2000-07-09 15:48:49 +00001471PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001472{
1473 if (x == NULL)
1474 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001475 if (PyInstance_Check(x)) {
1476 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001477 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001478 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001479 return 0;
1480 }
1481 /* Could test recursively but don't, for fear of endless
1482 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001483 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001484 return 1;
1485 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001486 else {
1487 return x->ob_type->tp_call != NULL;
1488 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001489}
1490
Tim Peters7eea37e2001-09-04 22:08:56 +00001491/* Helper for PyObject_Dir.
1492 Merge the __dict__ of aclass into dict, and recursively also all
1493 the __dict__s of aclass's base classes. The order of merging isn't
1494 defined, as it's expected that only the final set of dict keys is
1495 interesting.
1496 Return 0 on success, -1 on error.
1497*/
1498
1499static int
1500merge_class_dict(PyObject* dict, PyObject* aclass)
1501{
1502 PyObject *classdict;
1503 PyObject *bases;
1504
1505 assert(PyDict_Check(dict));
1506 assert(aclass);
1507
1508 /* Merge in the type's dict (if any). */
1509 classdict = PyObject_GetAttrString(aclass, "__dict__");
1510 if (classdict == NULL)
1511 PyErr_Clear();
1512 else {
1513 int status = PyDict_Update(dict, classdict);
1514 Py_DECREF(classdict);
1515 if (status < 0)
1516 return -1;
1517 }
1518
1519 /* Recursively merge in the base types' (if any) dicts. */
1520 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001521 if (bases == NULL)
1522 PyErr_Clear();
1523 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001524 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001525 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001526 n = PySequence_Size(bases); /* This better be right */
1527 if (n < 0)
1528 PyErr_Clear();
1529 else {
1530 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001531 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001532 PyObject *base = PySequence_GetItem(bases, i);
1533 if (base == NULL) {
1534 Py_DECREF(bases);
1535 return -1;
1536 }
Tim Peters18e70832003-02-05 19:35:19 +00001537 status = merge_class_dict(dict, base);
1538 Py_DECREF(base);
1539 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001540 Py_DECREF(bases);
1541 return -1;
1542 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001543 }
1544 }
1545 Py_DECREF(bases);
1546 }
1547 return 0;
1548}
1549
Tim Peters305b5852001-09-17 02:38:46 +00001550/* Helper for PyObject_Dir.
1551 If obj has an attr named attrname that's a list, merge its string
1552 elements into keys of dict.
1553 Return 0 on success, -1 on error. Errors due to not finding the attr,
1554 or the attr not being a list, are suppressed.
1555*/
1556
1557static int
1558merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1559{
1560 PyObject *list;
1561 int result = 0;
1562
1563 assert(PyDict_Check(dict));
1564 assert(obj);
1565 assert(attrname);
1566
1567 list = PyObject_GetAttrString(obj, attrname);
1568 if (list == NULL)
1569 PyErr_Clear();
1570
1571 else if (PyList_Check(list)) {
1572 int i;
1573 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1574 PyObject *item = PyList_GET_ITEM(list, i);
1575 if (PyString_Check(item)) {
1576 result = PyDict_SetItem(dict, item, Py_None);
1577 if (result < 0)
1578 break;
1579 }
1580 }
1581 }
1582
1583 Py_XDECREF(list);
1584 return result;
1585}
1586
Tim Peters7eea37e2001-09-04 22:08:56 +00001587/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1588 docstring, which should be kept in synch with this implementation. */
1589
1590PyObject *
1591PyObject_Dir(PyObject *arg)
1592{
1593 /* Set exactly one of these non-NULL before the end. */
1594 PyObject *result = NULL; /* result list */
1595 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1596
1597 /* If NULL arg, return the locals. */
1598 if (arg == NULL) {
1599 PyObject *locals = PyEval_GetLocals();
1600 if (locals == NULL)
1601 goto error;
1602 result = PyDict_Keys(locals);
1603 if (result == NULL)
1604 goto error;
1605 }
1606
1607 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001608 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001609 masterdict = PyObject_GetAttrString(arg, "__dict__");
1610 if (masterdict == NULL)
1611 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001612 if (!PyDict_Check(masterdict)) {
1613 PyErr_SetString(PyExc_TypeError,
1614 "module.__dict__ is not a dictionary");
1615 goto error;
1616 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001617 }
1618
1619 /* Elif some form of type or class, grab its dict and its bases.
1620 We deliberately don't suck up its __class__, as methods belonging
1621 to the metaclass would probably be more confusing than helpful. */
1622 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1623 masterdict = PyDict_New();
1624 if (masterdict == NULL)
1625 goto error;
1626 if (merge_class_dict(masterdict, arg) < 0)
1627 goto error;
1628 }
1629
1630 /* Else look at its dict, and the attrs reachable from its class. */
1631 else {
1632 PyObject *itsclass;
1633 /* Create a dict to start with. CAUTION: Not everything
1634 responding to __dict__ returns a dict! */
1635 masterdict = PyObject_GetAttrString(arg, "__dict__");
1636 if (masterdict == NULL) {
1637 PyErr_Clear();
1638 masterdict = PyDict_New();
1639 }
1640 else if (!PyDict_Check(masterdict)) {
1641 Py_DECREF(masterdict);
1642 masterdict = PyDict_New();
1643 }
1644 else {
1645 /* The object may have returned a reference to its
1646 dict, so copy it to avoid mutating it. */
1647 PyObject *temp = PyDict_Copy(masterdict);
1648 Py_DECREF(masterdict);
1649 masterdict = temp;
1650 }
1651 if (masterdict == NULL)
1652 goto error;
1653
Tim Peters305b5852001-09-17 02:38:46 +00001654 /* Merge in __members__ and __methods__ (if any).
1655 XXX Would like this to go away someday; for now, it's
1656 XXX needed to get at im_self etc of method objects. */
1657 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1658 goto error;
1659 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1660 goto error;
1661
Tim Peters7eea37e2001-09-04 22:08:56 +00001662 /* Merge in attrs reachable from its class.
1663 CAUTION: Not all objects have a __class__ attr. */
1664 itsclass = PyObject_GetAttrString(arg, "__class__");
1665 if (itsclass == NULL)
1666 PyErr_Clear();
1667 else {
1668 int status = merge_class_dict(masterdict, itsclass);
1669 Py_DECREF(itsclass);
1670 if (status < 0)
1671 goto error;
1672 }
1673 }
1674
1675 assert((result == NULL) ^ (masterdict == NULL));
1676 if (masterdict != NULL) {
1677 /* The result comes from its keys. */
1678 assert(result == NULL);
1679 result = PyDict_Keys(masterdict);
1680 if (result == NULL)
1681 goto error;
1682 }
1683
1684 assert(result);
1685 if (PyList_Sort(result) != 0)
1686 goto error;
1687 else
1688 goto normal_return;
1689
1690 error:
1691 Py_XDECREF(result);
1692 result = NULL;
1693 /* fall through */
1694 normal_return:
1695 Py_XDECREF(masterdict);
1696 return result;
1697}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001698
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001699/*
1700NoObject is usable as a non-NULL undefined value, used by the macro None.
1701There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001702so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001703(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001704*/
1705
Guido van Rossum0c182a11992-03-27 17:26:13 +00001706/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001707static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001708none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001709{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001710 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001711}
1712
Barry Warsaw9bf16442001-01-23 16:24:35 +00001713/* ARGUSED */
1714static void
Tim Peters803526b2002-07-07 05:13:56 +00001715none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001716{
1717 /* This should never get called, but we also don't want to SEGV if
1718 * we accidently decref None out of existance.
1719 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001720 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001721}
1722
1723
Guido van Rossumba21a492001-08-16 08:17:26 +00001724static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001725 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001726 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001727 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001728 0,
1729 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001730 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001731 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001732 0, /*tp_getattr*/
1733 0, /*tp_setattr*/
1734 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001735 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001736 0, /*tp_as_number*/
1737 0, /*tp_as_sequence*/
1738 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001739 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740};
1741
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001742PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001743 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001744};
1745
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001746/* NotImplemented is an object that can be used to signal that an
1747 operation is not implemented for the given type combination. */
1748
1749static PyObject *
1750NotImplemented_repr(PyObject *op)
1751{
1752 return PyString_FromString("NotImplemented");
1753}
1754
1755static PyTypeObject PyNotImplemented_Type = {
1756 PyObject_HEAD_INIT(&PyType_Type)
1757 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001758 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001759 0,
1760 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001761 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001762 0, /*tp_print*/
1763 0, /*tp_getattr*/
1764 0, /*tp_setattr*/
1765 0, /*tp_compare*/
1766 (reprfunc)NotImplemented_repr, /*tp_repr*/
1767 0, /*tp_as_number*/
1768 0, /*tp_as_sequence*/
1769 0, /*tp_as_mapping*/
1770 0, /*tp_hash */
1771};
1772
1773PyObject _Py_NotImplementedStruct = {
1774 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1775};
1776
Guido van Rossumba21a492001-08-16 08:17:26 +00001777void
1778_Py_ReadyTypes(void)
1779{
1780 if (PyType_Ready(&PyType_Type) < 0)
1781 Py_FatalError("Can't initialize 'type'");
1782
Guido van Rossum77f6a652002-04-03 22:41:51 +00001783 if (PyType_Ready(&PyBool_Type) < 0)
1784 Py_FatalError("Can't initialize 'bool'");
1785
Guido van Rossumcacfc072002-05-24 19:01:59 +00001786 if (PyType_Ready(&PyString_Type) < 0)
1787 Py_FatalError("Can't initialize 'str'");
1788
Guido van Rossumba21a492001-08-16 08:17:26 +00001789 if (PyType_Ready(&PyList_Type) < 0)
1790 Py_FatalError("Can't initialize 'list'");
1791
1792 if (PyType_Ready(&PyNone_Type) < 0)
1793 Py_FatalError("Can't initialize type(None)");
1794
1795 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1796 Py_FatalError("Can't initialize type(NotImplemented)");
1797}
1798
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001799
Guido van Rossum84a90321996-05-22 16:34:47 +00001800#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001801
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001802void
Fred Drake100814d2000-07-09 15:48:49 +00001803_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001804{
Tim Peters34592512002-07-11 06:23:50 +00001805 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001806 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001807 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001808 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001809}
1810
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001811void
Fred Drake100814d2000-07-09 15:48:49 +00001812_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001813{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001814#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001815 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001816#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001817 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001818 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001819 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001820 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001821 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001822#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001823 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1824 if (p == op)
1825 break;
1826 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001827 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001828 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001829#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001830 op->_ob_next->_ob_prev = op->_ob_prev;
1831 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001832 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001833 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001834}
1835
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001836void
Fred Drake100814d2000-07-09 15:48:49 +00001837_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001838{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001839 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001840 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001841 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842}
1843
Tim Peters269b2a62003-04-17 19:52:29 +00001844/* Print all live objects. Because PyObject_Print is called, the
1845 * interpreter must be in a healthy state.
1846 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001847void
Fred Drake100814d2000-07-09 15:48:49 +00001848_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001851 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001852 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001853 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001854 if (PyObject_Print(op, fp, 0) != 0)
1855 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001856 putc('\n', fp);
1857 }
1858}
1859
Tim Peters269b2a62003-04-17 19:52:29 +00001860/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1861 * doesn't make any calls to the Python C API, so is always safe to call.
1862 */
1863void
1864_Py_PrintReferenceAddresses(FILE *fp)
1865{
1866 PyObject *op;
1867 fprintf(fp, "Remaining object addresses:\n");
1868 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001869 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1870 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001871}
1872
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001873PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001874_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001875{
1876 int i, n;
1877 PyObject *t = NULL;
1878 PyObject *res, *op;
1879
1880 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1881 return NULL;
1882 op = refchain._ob_next;
1883 res = PyList_New(0);
1884 if (res == NULL)
1885 return NULL;
1886 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1887 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001888 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001889 op = op->_ob_next;
1890 if (op == &refchain)
1891 return res;
1892 }
1893 if (PyList_Append(res, op) < 0) {
1894 Py_DECREF(res);
1895 return NULL;
1896 }
1897 op = op->_ob_next;
1898 }
1899 return res;
1900}
1901
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001902#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001903
1904
1905/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001906PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001907
1908
1909/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001910int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001911
1912
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001913/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001914
Thomas Wouters334fb892000-07-25 12:56:38 +00001915void *
Fred Drake100814d2000-07-09 15:48:49 +00001916PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001917{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001918 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001919}
1920
Thomas Wouters334fb892000-07-25 12:56:38 +00001921void *
1922PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001923{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001924 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001925}
1926
1927void
Thomas Wouters334fb892000-07-25 12:56:38 +00001928PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001929{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001930 PyMem_FREE(p);
1931}
1932
1933
Guido van Rossum86610361998-04-10 22:32:46 +00001934/* These methods are used to control infinite recursion in repr, str, print,
1935 etc. Container objects that may recursively contain themselves,
1936 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1937 Py_ReprLeave() to avoid infinite recursion.
1938
1939 Py_ReprEnter() returns 0 the first time it is called for a particular
1940 object and 1 every time thereafter. It returns -1 if an exception
1941 occurred. Py_ReprLeave() has no return value.
1942
1943 See dictobject.c and listobject.c for examples of use.
1944*/
1945
1946#define KEY "Py_Repr"
1947
1948int
Fred Drake100814d2000-07-09 15:48:49 +00001949Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001950{
1951 PyObject *dict;
1952 PyObject *list;
1953 int i;
1954
1955 dict = PyThreadState_GetDict();
1956 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001957 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001958 list = PyDict_GetItemString(dict, KEY);
1959 if (list == NULL) {
1960 list = PyList_New(0);
1961 if (list == NULL)
1962 return -1;
1963 if (PyDict_SetItemString(dict, KEY, list) < 0)
1964 return -1;
1965 Py_DECREF(list);
1966 }
1967 i = PyList_GET_SIZE(list);
1968 while (--i >= 0) {
1969 if (PyList_GET_ITEM(list, i) == obj)
1970 return 1;
1971 }
1972 PyList_Append(list, obj);
1973 return 0;
1974}
1975
1976void
Fred Drake100814d2000-07-09 15:48:49 +00001977Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001978{
1979 PyObject *dict;
1980 PyObject *list;
1981 int i;
1982
1983 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001984 if (dict == NULL)
1985 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001986 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001987 if (list == NULL || !PyList_Check(list))
1988 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001989 i = PyList_GET_SIZE(list);
1990 /* Count backwards because we always expect obj to be list[-1] */
1991 while (--i >= 0) {
1992 if (PyList_GET_ITEM(list, i) == obj) {
1993 PyList_SetSlice(list, i, i + 1, NULL);
1994 break;
1995 }
1996 }
1997}
Guido van Rossumd724b232000-03-13 16:01:29 +00001998
Tim Peters803526b2002-07-07 05:13:56 +00001999/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002000
Tim Peters803526b2002-07-07 05:13:56 +00002001/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002002int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002003
Tim Peters803526b2002-07-07 05:13:56 +00002004/* List of objects that still need to be cleaned up, singly linked via their
2005 * gc headers' gc_prev pointers.
2006 */
2007PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002008
Tim Peters803526b2002-07-07 05:13:56 +00002009/* Add op to the _PyTrash_delete_later list. Called when the current
2010 * call-stack depth gets large. op must be a currently untracked gc'ed
2011 * object, with refcount 0. Py_DECREF must already have been called on it.
2012 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002013void
Fred Drake100814d2000-07-09 15:48:49 +00002014_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002015{
Tim Peters803526b2002-07-07 05:13:56 +00002016 assert(PyObject_IS_GC(op));
2017 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2018 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002019 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002020 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002021}
2022
Tim Peters803526b2002-07-07 05:13:56 +00002023/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2024 * the call-stack unwinds again.
2025 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002026void
Fred Drake100814d2000-07-09 15:48:49 +00002027_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002028{
2029 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002030 PyObject *op = _PyTrash_delete_later;
2031 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002032
Neil Schemenauerf589c052002-03-29 03:05:54 +00002033 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002034 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002035
Tim Peters803526b2002-07-07 05:13:56 +00002036 /* Call the deallocator directly. This used to try to
2037 * fool Py_DECREF into calling it indirectly, but
2038 * Py_DECREF was already called on this object, and in
2039 * assorted non-release builds calling Py_DECREF again ends
2040 * up distorting allocation statistics.
2041 */
2042 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002043 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002044 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002045 --_PyTrash_delete_nesting;
2046 }
2047}