blob: ba9a1d93b119a9f43ebd98634b49fa7d100e8268 [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{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000874 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000875 int ok;
876
Raymond Hettinger93d44812004-03-21 17:01:44 +0000877 /* Quick result when objects are the same.
878 Guarantees that identity implies equality. */
879 if (v == w) {
880 if (op == Py_EQ)
881 return 1;
882 else if (op == Py_NE)
883 return 0;
884 }
885
886 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000887 if (res == NULL)
888 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000889 if (PyBool_Check(res))
890 ok = (res == Py_True);
891 else
892 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000893 Py_DECREF(res);
894 return ok;
895}
Fred Drake13634cf2000-06-29 19:17:04 +0000896
897/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000898 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000899
900 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
901*/
902
903long
Fred Drake100814d2000-07-09 15:48:49 +0000904_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000905{
Tim Peters39dce292000-08-15 03:34:48 +0000906 double intpart, fractpart;
907 int expo;
908 long hipart;
909 long x; /* the final hash value */
910 /* This is designed so that Python numbers of different types
911 * that compare equal hash to the same value; otherwise comparisons
912 * of mapping keys will turn out weird.
913 */
914
Tim Peters39dce292000-08-15 03:34:48 +0000915 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000916 if (fractpart == 0.0) {
917 /* This must return the same hash as an equal int or long. */
918 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
919 /* Convert to long and use its hash. */
920 PyObject *plong; /* converted to Python long */
921 if (Py_IS_INFINITY(intpart))
922 /* can't convert to long int -- arbitrary */
923 v = v < 0 ? -271828.0 : 314159.0;
924 plong = PyLong_FromDouble(v);
925 if (plong == NULL)
926 return -1;
927 x = PyObject_Hash(plong);
928 Py_DECREF(plong);
929 return x;
930 }
931 /* Fits in a C long == a Python int, so is its own hash. */
932 x = (long)intpart;
933 if (x == -1)
934 x = -2;
935 return x;
936 }
937 /* The fractional part is non-zero, so we don't have to worry about
938 * making this match the hash of some other type.
939 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000940 * Since the VAX D double format has 56 mantissa bits, which is the
941 * most of any double format in use, each of these parts may have as
942 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000943 * So, assuming sizeof(long) >= 4, each part can be broken into two
944 * longs; frexp and multiplication are used to do that.
945 * Also, since the Cray double format has 15 exponent bits, which is
946 * the most of any double format in use, shifting the exponent field
947 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000948 */
Tim Peters39dce292000-08-15 03:34:48 +0000949 v = frexp(v, &expo);
950 v *= 2147483648.0; /* 2**31 */
951 hipart = (long)v; /* take the top 32 bits */
952 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
953 x = hipart + (long)v + (expo << 15);
954 if (x == -1)
955 x = -2;
956 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000957}
958
959long
Fred Drake100814d2000-07-09 15:48:49 +0000960_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000961{
962#if SIZEOF_LONG >= SIZEOF_VOID_P
963 return (long)p;
964#else
965 /* convert to a Python long and hash that */
966 PyObject* longobj;
967 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000968
Fred Drake13634cf2000-06-29 19:17:04 +0000969 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
970 x = -1;
971 goto finally;
972 }
973 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000974
Fred Drake13634cf2000-06-29 19:17:04 +0000975finally:
976 Py_XDECREF(longobj);
977 return x;
978#endif
979}
980
981
Guido van Rossum9bfef441993-03-29 10:43:31 +0000982long
Fred Drake100814d2000-07-09 15:48:49 +0000983PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000984{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000985 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000986 if (tp->tp_hash != NULL)
987 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000988 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000989 return _Py_HashPointer(v); /* Use address as hash value */
990 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000991 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000993 return -1;
994}
995
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000996PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000997PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000998{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000999 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001000
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001002 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 w = PyString_InternFromString(name);
1004 if (w == NULL)
1005 return NULL;
1006 res = PyObject_GetAttr(v, w);
1007 Py_XDECREF(w);
1008 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001009}
1010
1011int
Fred Drake100814d2000-07-09 15:48:49 +00001012PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001013{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001014 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001015 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001016 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001017 return 1;
1018 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001020 return 0;
1021}
1022
1023int
Fred Drake100814d2000-07-09 15:48:49 +00001024PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001025{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001026 PyObject *s;
1027 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001028
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001030 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031 s = PyString_InternFromString(name);
1032 if (s == NULL)
1033 return -1;
1034 res = PyObject_SetAttr(v, s, w);
1035 Py_XDECREF(s);
1036 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001037}
1038
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001039PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001040PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001041{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042 PyTypeObject *tp = v->ob_type;
1043
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001044 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001045#ifdef Py_USING_UNICODE
1046 /* The Unicode to string conversion is done here because the
1047 existing tp_getattro slots expect a string object as name
1048 and we wouldn't want to break those. */
1049 if (PyUnicode_Check(name)) {
1050 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1051 if (name == NULL)
1052 return NULL;
1053 }
1054 else
1055#endif
1056 {
1057 PyErr_SetString(PyExc_TypeError,
1058 "attribute name must be string");
1059 return NULL;
1060 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001061 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001062 if (tp->tp_getattro != NULL)
1063 return (*tp->tp_getattro)(v, name);
1064 if (tp->tp_getattr != NULL)
1065 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1066 PyErr_Format(PyExc_AttributeError,
1067 "'%.50s' object has no attribute '%.400s'",
1068 tp->tp_name, PyString_AS_STRING(name));
1069 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001070}
1071
1072int
Fred Drake100814d2000-07-09 15:48:49 +00001073PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001074{
1075 PyObject *res = PyObject_GetAttr(v, name);
1076 if (res != NULL) {
1077 Py_DECREF(res);
1078 return 1;
1079 }
1080 PyErr_Clear();
1081 return 0;
1082}
1083
1084int
Fred Drake100814d2000-07-09 15:48:49 +00001085PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001086{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001087 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001088 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001089
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001090 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001091#ifdef Py_USING_UNICODE
1092 /* The Unicode to string conversion is done here because the
1093 existing tp_setattro slots expect a string object as name
1094 and we wouldn't want to break those. */
1095 if (PyUnicode_Check(name)) {
1096 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1097 if (name == NULL)
1098 return -1;
1099 }
Tim Peters803526b2002-07-07 05:13:56 +00001100 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001101#endif
1102 {
1103 PyErr_SetString(PyExc_TypeError,
1104 "attribute name must be string");
1105 return -1;
1106 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108 else
1109 Py_INCREF(name);
1110
1111 PyString_InternInPlace(&name);
1112 if (tp->tp_setattro != NULL) {
1113 err = (*tp->tp_setattro)(v, name, value);
1114 Py_DECREF(name);
1115 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001116 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117 if (tp->tp_setattr != NULL) {
1118 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1119 Py_DECREF(name);
1120 return err;
1121 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001122 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1124 PyErr_Format(PyExc_TypeError,
1125 "'%.100s' object has no attributes "
1126 "(%s .%.100s)",
1127 tp->tp_name,
1128 value==NULL ? "del" : "assign to",
1129 PyString_AS_STRING(name));
1130 else
1131 PyErr_Format(PyExc_TypeError,
1132 "'%.100s' object has only read-only attributes "
1133 "(%s .%.100s)",
1134 tp->tp_name,
1135 value==NULL ? "del" : "assign to",
1136 PyString_AS_STRING(name));
1137 return -1;
1138}
1139
1140/* Helper to get a pointer to an object's __dict__ slot, if any */
1141
1142PyObject **
1143_PyObject_GetDictPtr(PyObject *obj)
1144{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001145 long dictoffset;
1146 PyTypeObject *tp = obj->ob_type;
1147
1148 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1149 return NULL;
1150 dictoffset = tp->tp_dictoffset;
1151 if (dictoffset == 0)
1152 return NULL;
1153 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001154 int tsize;
1155 size_t size;
1156
1157 tsize = ((PyVarObject *)obj)->ob_size;
1158 if (tsize < 0)
1159 tsize = -tsize;
1160 size = _PyObject_VAR_SIZE(tp, tsize);
1161
Tim Peters6d483d32001-10-06 21:27:34 +00001162 dictoffset += (long)size;
1163 assert(dictoffset > 0);
1164 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 }
1166 return (PyObject **) ((char *)obj + dictoffset);
1167}
1168
1169/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1170
1171PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001172PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001173{
1174 Py_INCREF(obj);
1175 return obj;
1176}
1177
1178PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1180{
1181 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001182 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001183 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001185 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001186 PyObject **dictptr;
1187
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001188 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001189#ifdef Py_USING_UNICODE
1190 /* The Unicode to string conversion is done here because the
1191 existing tp_setattro slots expect a string object as name
1192 and we wouldn't want to break those. */
1193 if (PyUnicode_Check(name)) {
1194 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1195 if (name == NULL)
1196 return NULL;
1197 }
Tim Peters803526b2002-07-07 05:13:56 +00001198 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001199#endif
1200 {
1201 PyErr_SetString(PyExc_TypeError,
1202 "attribute name must be string");
1203 return NULL;
1204 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001205 }
1206 else
1207 Py_INCREF(name);
1208
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001210 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001211 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 }
1213
Guido van Rossum056fbf42002-08-19 19:22:50 +00001214 /* Inline _PyType_Lookup */
1215 {
1216 int i, n;
1217 PyObject *mro, *base, *dict;
1218
1219 /* Look in tp_dict of types in MRO */
1220 mro = tp->tp_mro;
1221 assert(mro != NULL);
1222 assert(PyTuple_Check(mro));
1223 n = PyTuple_GET_SIZE(mro);
1224 for (i = 0; i < n; i++) {
1225 base = PyTuple_GET_ITEM(mro, i);
1226 if (PyClass_Check(base))
1227 dict = ((PyClassObject *)base)->cl_dict;
1228 else {
1229 assert(PyType_Check(base));
1230 dict = ((PyTypeObject *)base)->tp_dict;
1231 }
1232 assert(dict && PyDict_Check(dict));
1233 descr = PyDict_GetItem(dict, name);
1234 if (descr != NULL)
1235 break;
1236 }
1237 }
1238
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001239 Py_XINCREF(descr);
1240
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001242 if (descr != NULL &&
1243 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001245 if (f != NULL && PyDescr_IsData(descr)) {
1246 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001247 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001248 goto done;
1249 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250 }
1251
Guido van Rossumc66ff442002-08-19 16:50:48 +00001252 /* Inline _PyObject_GetDictPtr */
1253 dictoffset = tp->tp_dictoffset;
1254 if (dictoffset != 0) {
1255 PyObject *dict;
1256 if (dictoffset < 0) {
1257 int tsize;
1258 size_t size;
1259
1260 tsize = ((PyVarObject *)obj)->ob_size;
1261 if (tsize < 0)
1262 tsize = -tsize;
1263 size = _PyObject_VAR_SIZE(tp, tsize);
1264
1265 dictoffset += (long)size;
1266 assert(dictoffset > 0);
1267 assert(dictoffset % SIZEOF_VOID_P == 0);
1268 }
1269 dictptr = (PyObject **) ((char *)obj + dictoffset);
1270 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001272 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 if (res != NULL) {
1274 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001275 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001276 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 }
1278 }
1279 }
1280
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001281 if (f != NULL) {
1282 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001283 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001284 goto done;
1285 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286
1287 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001288 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001289 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001290 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 }
1292
1293 PyErr_Format(PyExc_AttributeError,
1294 "'%.50s' object has no attribute '%.400s'",
1295 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001296 done:
1297 Py_DECREF(name);
1298 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299}
1300
1301int
1302PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1303{
1304 PyTypeObject *tp = obj->ob_type;
1305 PyObject *descr;
1306 descrsetfunc f;
1307 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001308 int res = -1;
1309
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001310 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001311#ifdef Py_USING_UNICODE
1312 /* The Unicode to string conversion is done here because the
1313 existing tp_setattro slots expect a string object as name
1314 and we wouldn't want to break those. */
1315 if (PyUnicode_Check(name)) {
1316 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1317 if (name == NULL)
1318 return -1;
1319 }
Tim Peters803526b2002-07-07 05:13:56 +00001320 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001321#endif
1322 {
1323 PyErr_SetString(PyExc_TypeError,
1324 "attribute name must be string");
1325 return -1;
1326 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001327 }
1328 else
1329 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330
1331 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001332 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001333 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334 }
1335
1336 descr = _PyType_Lookup(tp, name);
1337 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001338 if (descr != NULL &&
1339 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001341 if (f != NULL && PyDescr_IsData(descr)) {
1342 res = f(descr, obj, value);
1343 goto done;
1344 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345 }
1346
1347 dictptr = _PyObject_GetDictPtr(obj);
1348 if (dictptr != NULL) {
1349 PyObject *dict = *dictptr;
1350 if (dict == NULL && value != NULL) {
1351 dict = PyDict_New();
1352 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001353 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354 *dictptr = dict;
1355 }
1356 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357 if (value == NULL)
1358 res = PyDict_DelItem(dict, name);
1359 else
1360 res = PyDict_SetItem(dict, name, value);
1361 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1362 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001363 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 }
1365 }
1366
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001367 if (f != NULL) {
1368 res = f(descr, obj, value);
1369 goto done;
1370 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371
1372 if (descr == NULL) {
1373 PyErr_Format(PyExc_AttributeError,
1374 "'%.50s' object has no attribute '%.400s'",
1375 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001376 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 }
1378
1379 PyErr_Format(PyExc_AttributeError,
1380 "'%.50s' object attribute '%.400s' is read-only",
1381 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001382 done:
1383 Py_DECREF(name);
1384 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001385}
1386
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001387/* Test a value used as condition, e.g., in a for or if statement.
1388 Return -1 if an error occurred */
1389
1390int
Fred Drake100814d2000-07-09 15:48:49 +00001391PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001392{
1393 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001394 if (v == Py_True)
1395 return 1;
1396 if (v == Py_False)
1397 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001398 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001399 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001400 else if (v->ob_type->tp_as_number != NULL &&
1401 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001402 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001403 else if (v->ob_type->tp_as_mapping != NULL &&
1404 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001405 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001406 else if (v->ob_type->tp_as_sequence != NULL &&
1407 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001408 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1409 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001410 return 1;
1411 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001412}
1413
Tim Peters803526b2002-07-07 05:13:56 +00001414/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001415 Return -1 if an error occurred */
1416
1417int
Fred Drake100814d2000-07-09 15:48:49 +00001418PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001419{
1420 int res;
1421 res = PyObject_IsTrue(v);
1422 if (res < 0)
1423 return res;
1424 return res == 0;
1425}
1426
Guido van Rossum5524a591995-01-10 15:26:20 +00001427/* Coerce two numeric types to the "larger" one.
1428 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001429 Return value:
1430 -1 if an error occurred;
1431 0 if the coercion succeeded (and then the reference counts are increased);
1432 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001433*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001434int
Fred Drake100814d2000-07-09 15:48:49 +00001435PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001436{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001437 register PyObject *v = *pv;
1438 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001439 int res;
1440
Guido van Rossum517c7d42002-04-26 02:49:14 +00001441 /* Shortcut only for old-style types */
1442 if (v->ob_type == w->ob_type &&
1443 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1444 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001445 Py_INCREF(v);
1446 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001447 return 0;
1448 }
1449 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1450 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1451 if (res <= 0)
1452 return res;
1453 }
1454 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1455 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1456 if (res <= 0)
1457 return res;
1458 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001459 return 1;
1460}
1461
Guido van Rossume797ec12001-01-17 15:24:28 +00001462/* Coerce two numeric types to the "larger" one.
1463 Increment the reference count on each argument.
1464 Return -1 and raise an exception if no coercion is possible
1465 (and then no reference count is incremented).
1466*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001467int
Fred Drake100814d2000-07-09 15:48:49 +00001468PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001469{
1470 int err = PyNumber_CoerceEx(pv, pw);
1471 if (err <= 0)
1472 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001473 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001474 return -1;
1475}
1476
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001477
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001478/* Test whether an object can be called */
1479
1480int
Fred Drake100814d2000-07-09 15:48:49 +00001481PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001482{
1483 if (x == NULL)
1484 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001485 if (PyInstance_Check(x)) {
1486 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001487 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001488 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001489 return 0;
1490 }
1491 /* Could test recursively but don't, for fear of endless
1492 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001493 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001494 return 1;
1495 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 else {
1497 return x->ob_type->tp_call != NULL;
1498 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001499}
1500
Tim Peters7eea37e2001-09-04 22:08:56 +00001501/* Helper for PyObject_Dir.
1502 Merge the __dict__ of aclass into dict, and recursively also all
1503 the __dict__s of aclass's base classes. The order of merging isn't
1504 defined, as it's expected that only the final set of dict keys is
1505 interesting.
1506 Return 0 on success, -1 on error.
1507*/
1508
1509static int
1510merge_class_dict(PyObject* dict, PyObject* aclass)
1511{
1512 PyObject *classdict;
1513 PyObject *bases;
1514
1515 assert(PyDict_Check(dict));
1516 assert(aclass);
1517
1518 /* Merge in the type's dict (if any). */
1519 classdict = PyObject_GetAttrString(aclass, "__dict__");
1520 if (classdict == NULL)
1521 PyErr_Clear();
1522 else {
1523 int status = PyDict_Update(dict, classdict);
1524 Py_DECREF(classdict);
1525 if (status < 0)
1526 return -1;
1527 }
1528
1529 /* Recursively merge in the base types' (if any) dicts. */
1530 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001531 if (bases == NULL)
1532 PyErr_Clear();
1533 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001534 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001535 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001536 n = PySequence_Size(bases); /* This better be right */
1537 if (n < 0)
1538 PyErr_Clear();
1539 else {
1540 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001541 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001542 PyObject *base = PySequence_GetItem(bases, i);
1543 if (base == NULL) {
1544 Py_DECREF(bases);
1545 return -1;
1546 }
Tim Peters18e70832003-02-05 19:35:19 +00001547 status = merge_class_dict(dict, base);
1548 Py_DECREF(base);
1549 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001550 Py_DECREF(bases);
1551 return -1;
1552 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001553 }
1554 }
1555 Py_DECREF(bases);
1556 }
1557 return 0;
1558}
1559
Tim Peters305b5852001-09-17 02:38:46 +00001560/* Helper for PyObject_Dir.
1561 If obj has an attr named attrname that's a list, merge its string
1562 elements into keys of dict.
1563 Return 0 on success, -1 on error. Errors due to not finding the attr,
1564 or the attr not being a list, are suppressed.
1565*/
1566
1567static int
1568merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1569{
1570 PyObject *list;
1571 int result = 0;
1572
1573 assert(PyDict_Check(dict));
1574 assert(obj);
1575 assert(attrname);
1576
1577 list = PyObject_GetAttrString(obj, attrname);
1578 if (list == NULL)
1579 PyErr_Clear();
1580
1581 else if (PyList_Check(list)) {
1582 int i;
1583 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1584 PyObject *item = PyList_GET_ITEM(list, i);
1585 if (PyString_Check(item)) {
1586 result = PyDict_SetItem(dict, item, Py_None);
1587 if (result < 0)
1588 break;
1589 }
1590 }
1591 }
1592
1593 Py_XDECREF(list);
1594 return result;
1595}
1596
Tim Peters7eea37e2001-09-04 22:08:56 +00001597/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1598 docstring, which should be kept in synch with this implementation. */
1599
1600PyObject *
1601PyObject_Dir(PyObject *arg)
1602{
1603 /* Set exactly one of these non-NULL before the end. */
1604 PyObject *result = NULL; /* result list */
1605 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1606
1607 /* If NULL arg, return the locals. */
1608 if (arg == NULL) {
1609 PyObject *locals = PyEval_GetLocals();
1610 if (locals == NULL)
1611 goto error;
1612 result = PyDict_Keys(locals);
1613 if (result == NULL)
1614 goto error;
1615 }
1616
1617 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001618 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001619 masterdict = PyObject_GetAttrString(arg, "__dict__");
1620 if (masterdict == NULL)
1621 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001622 if (!PyDict_Check(masterdict)) {
1623 PyErr_SetString(PyExc_TypeError,
1624 "module.__dict__ is not a dictionary");
1625 goto error;
1626 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001627 }
1628
1629 /* Elif some form of type or class, grab its dict and its bases.
1630 We deliberately don't suck up its __class__, as methods belonging
1631 to the metaclass would probably be more confusing than helpful. */
1632 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1633 masterdict = PyDict_New();
1634 if (masterdict == NULL)
1635 goto error;
1636 if (merge_class_dict(masterdict, arg) < 0)
1637 goto error;
1638 }
1639
1640 /* Else look at its dict, and the attrs reachable from its class. */
1641 else {
1642 PyObject *itsclass;
1643 /* Create a dict to start with. CAUTION: Not everything
1644 responding to __dict__ returns a dict! */
1645 masterdict = PyObject_GetAttrString(arg, "__dict__");
1646 if (masterdict == NULL) {
1647 PyErr_Clear();
1648 masterdict = PyDict_New();
1649 }
1650 else if (!PyDict_Check(masterdict)) {
1651 Py_DECREF(masterdict);
1652 masterdict = PyDict_New();
1653 }
1654 else {
1655 /* The object may have returned a reference to its
1656 dict, so copy it to avoid mutating it. */
1657 PyObject *temp = PyDict_Copy(masterdict);
1658 Py_DECREF(masterdict);
1659 masterdict = temp;
1660 }
1661 if (masterdict == NULL)
1662 goto error;
1663
Tim Peters305b5852001-09-17 02:38:46 +00001664 /* Merge in __members__ and __methods__ (if any).
1665 XXX Would like this to go away someday; for now, it's
1666 XXX needed to get at im_self etc of method objects. */
1667 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1668 goto error;
1669 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1670 goto error;
1671
Tim Peters7eea37e2001-09-04 22:08:56 +00001672 /* Merge in attrs reachable from its class.
1673 CAUTION: Not all objects have a __class__ attr. */
1674 itsclass = PyObject_GetAttrString(arg, "__class__");
1675 if (itsclass == NULL)
1676 PyErr_Clear();
1677 else {
1678 int status = merge_class_dict(masterdict, itsclass);
1679 Py_DECREF(itsclass);
1680 if (status < 0)
1681 goto error;
1682 }
1683 }
1684
1685 assert((result == NULL) ^ (masterdict == NULL));
1686 if (masterdict != NULL) {
1687 /* The result comes from its keys. */
1688 assert(result == NULL);
1689 result = PyDict_Keys(masterdict);
1690 if (result == NULL)
1691 goto error;
1692 }
1693
1694 assert(result);
1695 if (PyList_Sort(result) != 0)
1696 goto error;
1697 else
1698 goto normal_return;
1699
1700 error:
1701 Py_XDECREF(result);
1702 result = NULL;
1703 /* fall through */
1704 normal_return:
1705 Py_XDECREF(masterdict);
1706 return result;
1707}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001708
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001709/*
1710NoObject is usable as a non-NULL undefined value, used by the macro None.
1711There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001712so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001713(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001714*/
1715
Guido van Rossum0c182a11992-03-27 17:26:13 +00001716/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001717static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001718none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001719{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001720 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001721}
1722
Barry Warsaw9bf16442001-01-23 16:24:35 +00001723/* ARGUSED */
1724static void
Tim Peters803526b2002-07-07 05:13:56 +00001725none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001726{
1727 /* This should never get called, but we also don't want to SEGV if
1728 * we accidently decref None out of existance.
1729 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001730 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001731}
1732
1733
Guido van Rossumba21a492001-08-16 08:17:26 +00001734static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001735 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001736 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001737 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001738 0,
1739 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001740 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001741 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001742 0, /*tp_getattr*/
1743 0, /*tp_setattr*/
1744 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001745 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001746 0, /*tp_as_number*/
1747 0, /*tp_as_sequence*/
1748 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001749 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750};
1751
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001752PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001753 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001754};
1755
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001756/* NotImplemented is an object that can be used to signal that an
1757 operation is not implemented for the given type combination. */
1758
1759static PyObject *
1760NotImplemented_repr(PyObject *op)
1761{
1762 return PyString_FromString("NotImplemented");
1763}
1764
1765static PyTypeObject PyNotImplemented_Type = {
1766 PyObject_HEAD_INIT(&PyType_Type)
1767 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001768 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001769 0,
1770 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001771 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001772 0, /*tp_print*/
1773 0, /*tp_getattr*/
1774 0, /*tp_setattr*/
1775 0, /*tp_compare*/
1776 (reprfunc)NotImplemented_repr, /*tp_repr*/
1777 0, /*tp_as_number*/
1778 0, /*tp_as_sequence*/
1779 0, /*tp_as_mapping*/
1780 0, /*tp_hash */
1781};
1782
1783PyObject _Py_NotImplementedStruct = {
1784 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1785};
1786
Guido van Rossumba21a492001-08-16 08:17:26 +00001787void
1788_Py_ReadyTypes(void)
1789{
1790 if (PyType_Ready(&PyType_Type) < 0)
1791 Py_FatalError("Can't initialize 'type'");
1792
Guido van Rossum77f6a652002-04-03 22:41:51 +00001793 if (PyType_Ready(&PyBool_Type) < 0)
1794 Py_FatalError("Can't initialize 'bool'");
1795
Guido van Rossumcacfc072002-05-24 19:01:59 +00001796 if (PyType_Ready(&PyString_Type) < 0)
1797 Py_FatalError("Can't initialize 'str'");
1798
Guido van Rossumba21a492001-08-16 08:17:26 +00001799 if (PyType_Ready(&PyList_Type) < 0)
1800 Py_FatalError("Can't initialize 'list'");
1801
1802 if (PyType_Ready(&PyNone_Type) < 0)
1803 Py_FatalError("Can't initialize type(None)");
1804
1805 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1806 Py_FatalError("Can't initialize type(NotImplemented)");
1807}
1808
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001809
Guido van Rossum84a90321996-05-22 16:34:47 +00001810#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001811
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001812void
Fred Drake100814d2000-07-09 15:48:49 +00001813_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001814{
Tim Peters34592512002-07-11 06:23:50 +00001815 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001816 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001817 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001818 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819}
1820
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001821void
Fred Drake100814d2000-07-09 15:48:49 +00001822_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001823{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001824#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001825 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001826#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001827 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001828 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001829 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001830 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001831 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001832#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001833 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1834 if (p == op)
1835 break;
1836 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001837 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001838 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001839#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001840 op->_ob_next->_ob_prev = op->_ob_prev;
1841 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001842 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001843 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001844}
1845
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001846void
Fred Drake100814d2000-07-09 15:48:49 +00001847_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001848{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001849 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001851 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001852}
1853
Tim Peters269b2a62003-04-17 19:52:29 +00001854/* Print all live objects. Because PyObject_Print is called, the
1855 * interpreter must be in a healthy state.
1856 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001857void
Fred Drake100814d2000-07-09 15:48:49 +00001858_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001859{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001860 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001861 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001862 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001863 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001864 if (PyObject_Print(op, fp, 0) != 0)
1865 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001866 putc('\n', fp);
1867 }
1868}
1869
Tim Peters269b2a62003-04-17 19:52:29 +00001870/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1871 * doesn't make any calls to the Python C API, so is always safe to call.
1872 */
1873void
1874_Py_PrintReferenceAddresses(FILE *fp)
1875{
1876 PyObject *op;
1877 fprintf(fp, "Remaining object addresses:\n");
1878 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001879 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1880 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001881}
1882
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001883PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001884_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001885{
1886 int i, n;
1887 PyObject *t = NULL;
1888 PyObject *res, *op;
1889
1890 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1891 return NULL;
1892 op = refchain._ob_next;
1893 res = PyList_New(0);
1894 if (res == NULL)
1895 return NULL;
1896 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1897 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001898 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001899 op = op->_ob_next;
1900 if (op == &refchain)
1901 return res;
1902 }
1903 if (PyList_Append(res, op) < 0) {
1904 Py_DECREF(res);
1905 return NULL;
1906 }
1907 op = op->_ob_next;
1908 }
1909 return res;
1910}
1911
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001912#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001913
1914
1915/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001916PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001917
1918
1919/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001920int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001921
1922
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001923/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001924
Thomas Wouters334fb892000-07-25 12:56:38 +00001925void *
Fred Drake100814d2000-07-09 15:48:49 +00001926PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001927{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001928 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001929}
1930
Thomas Wouters334fb892000-07-25 12:56:38 +00001931void *
1932PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001933{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001934 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001935}
1936
1937void
Thomas Wouters334fb892000-07-25 12:56:38 +00001938PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001939{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001940 PyMem_FREE(p);
1941}
1942
1943
Guido van Rossum86610361998-04-10 22:32:46 +00001944/* These methods are used to control infinite recursion in repr, str, print,
1945 etc. Container objects that may recursively contain themselves,
1946 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1947 Py_ReprLeave() to avoid infinite recursion.
1948
1949 Py_ReprEnter() returns 0 the first time it is called for a particular
1950 object and 1 every time thereafter. It returns -1 if an exception
1951 occurred. Py_ReprLeave() has no return value.
1952
1953 See dictobject.c and listobject.c for examples of use.
1954*/
1955
1956#define KEY "Py_Repr"
1957
1958int
Fred Drake100814d2000-07-09 15:48:49 +00001959Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001960{
1961 PyObject *dict;
1962 PyObject *list;
1963 int i;
1964
1965 dict = PyThreadState_GetDict();
1966 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001967 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001968 list = PyDict_GetItemString(dict, KEY);
1969 if (list == NULL) {
1970 list = PyList_New(0);
1971 if (list == NULL)
1972 return -1;
1973 if (PyDict_SetItemString(dict, KEY, list) < 0)
1974 return -1;
1975 Py_DECREF(list);
1976 }
1977 i = PyList_GET_SIZE(list);
1978 while (--i >= 0) {
1979 if (PyList_GET_ITEM(list, i) == obj)
1980 return 1;
1981 }
1982 PyList_Append(list, obj);
1983 return 0;
1984}
1985
1986void
Fred Drake100814d2000-07-09 15:48:49 +00001987Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001988{
1989 PyObject *dict;
1990 PyObject *list;
1991 int i;
1992
1993 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001994 if (dict == NULL)
1995 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001996 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001997 if (list == NULL || !PyList_Check(list))
1998 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001999 i = PyList_GET_SIZE(list);
2000 /* Count backwards because we always expect obj to be list[-1] */
2001 while (--i >= 0) {
2002 if (PyList_GET_ITEM(list, i) == obj) {
2003 PyList_SetSlice(list, i, i + 1, NULL);
2004 break;
2005 }
2006 }
2007}
Guido van Rossumd724b232000-03-13 16:01:29 +00002008
Tim Peters803526b2002-07-07 05:13:56 +00002009/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002010
Tim Peters803526b2002-07-07 05:13:56 +00002011/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002012int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002013
Tim Peters803526b2002-07-07 05:13:56 +00002014/* List of objects that still need to be cleaned up, singly linked via their
2015 * gc headers' gc_prev pointers.
2016 */
2017PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002018
Tim Peters803526b2002-07-07 05:13:56 +00002019/* Add op to the _PyTrash_delete_later list. Called when the current
2020 * call-stack depth gets large. op must be a currently untracked gc'ed
2021 * object, with refcount 0. Py_DECREF must already have been called on it.
2022 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002023void
Fred Drake100814d2000-07-09 15:48:49 +00002024_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002025{
Tim Peters803526b2002-07-07 05:13:56 +00002026 assert(PyObject_IS_GC(op));
2027 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2028 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002029 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002030 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002031}
2032
Tim Peters803526b2002-07-07 05:13:56 +00002033/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2034 * the call-stack unwinds again.
2035 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002036void
Fred Drake100814d2000-07-09 15:48:49 +00002037_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002038{
2039 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002040 PyObject *op = _PyTrash_delete_later;
2041 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002042
Neil Schemenauerf589c052002-03-29 03:05:54 +00002043 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002044 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002045
Tim Peters803526b2002-07-07 05:13:56 +00002046 /* Call the deallocator directly. This used to try to
2047 * fool Py_DECREF into calling it indirectly, but
2048 * Py_DECREF was already called on this object, and in
2049 * assorted non-release builds calling Py_DECREF again ends
2050 * up distorting allocation statistics.
2051 */
2052 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002053 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002054 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002055 --_PyTrash_delete_nesting;
2056 }
2057}