blob: 33e146ae9fb95b18b47d39a6f4e5933e9445d529 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jack Jansen28fc8802000-07-11 21:47:20 +00006#ifdef macintosh
7#include "macglue.h"
8#endif
9
Tim Peters34592512002-07-11 06:23:50 +000010#ifdef Py_REF_DEBUG
Mark Hammonda2905272002-07-29 13:42:14 +000011long _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Mark Hammonda2905272002-07-29 13:42:14 +000014int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000015
Guido van Rossum3f5da241990-12-20 15:06:42 +000016/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
17 These are used by the individual routines for object creation.
18 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000019
Tim Peters78be7992003-03-23 02:51:01 +000020#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000021/* Head of circular doubly-linked list of all objects. These are linked
22 * together via the _ob_prev and _ob_next members of a PyObject, which
23 * exist only in a Py_TRACE_REFS build.
24 */
Tim Peters78be7992003-03-23 02:51:01 +000025static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000026
Tim Peters7571a0f2003-03-23 17:52:28 +000027/* Insert op at the front of the list of all objects. If force is true,
28 * op is added even if _ob_prev and _ob_next are non-NULL already. If
29 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
30 * force should be true if and only if op points to freshly allocated,
31 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000032 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000033 * Note that objects are normally added to the list via _Py_NewReference,
34 * which is called by PyObject_Init. Not all objects are initialized that
35 * way, though; exceptions include statically allocated type objects, and
36 * statically allocated singletons (like Py_True and Py_None).
37 */
Tim Peters36eb4df2003-03-23 03:33:13 +000038void
Tim Peters7571a0f2003-03-23 17:52:28 +000039_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000040{
Tim Peters7571a0f2003-03-23 17:52:28 +000041#ifdef Py_DEBUG
42 if (!force) {
43 /* If it's initialized memory, op must be in or out of
44 * the list unambiguously.
45 */
46 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
47 }
Tim Peters78be7992003-03-23 02:51:01 +000048#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000049 if (force || op->_ob_prev == NULL) {
50 op->_ob_next = refchain._ob_next;
51 op->_ob_prev = &refchain;
52 refchain._ob_next->_ob_prev = op;
53 refchain._ob_next = op;
54 }
55}
56#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000057
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000058#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000059static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000060extern int tuple_zero_allocs, fast_tuple_allocs;
61extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000062extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000063void
Fred Drake100814d2000-07-09 15:48:49 +000064dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000065{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000067
68 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000069 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000070 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000071 tp->tp_maxalloc);
72 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
73 fast_tuple_allocs, tuple_zero_allocs);
74 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
75 quick_int_allocs, quick_neg_int_allocs);
76 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
77 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000078}
79
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000080PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000081get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000082{
83 PyTypeObject *tp;
84 PyObject *result;
85 PyObject *v;
86
87 result = PyList_New(0);
88 if (result == NULL)
89 return NULL;
90 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000091 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
92 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000093 if (v == NULL) {
94 Py_DECREF(result);
95 return NULL;
96 }
97 if (PyList_Append(result, v) < 0) {
98 Py_DECREF(v);
99 Py_DECREF(result);
100 return NULL;
101 }
102 Py_DECREF(v);
103 }
104 return result;
105}
106
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000107void
Fred Drake100814d2000-07-09 15:48:49 +0000108inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000109{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000111 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000112 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000114 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000115 /* Note that as of Python 2.2, heap-allocated type objects
116 * can go away, but this code requires that they stay alive
117 * until program exit. That's why we're careful with
118 * refcounts here. type_list gets a new reference to tp,
119 * while ownership of the reference type_list used to hold
120 * (if any) was transferred to tp->tp_next in the line above.
121 * tp is thus effectively immortal after this.
122 */
123 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000124 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000125#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000126 /* Also insert in the doubly-linked list of all objects,
127 * if not already there.
128 */
129 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000130#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000131 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000132 tp->tp_allocs++;
133 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
134 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000135}
136#endif
137
Tim Peters7c321a82002-07-09 02:57:01 +0000138#ifdef Py_REF_DEBUG
139/* Log a fatal error; doesn't return. */
140void
141_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
142{
143 char buf[300];
144
145 PyOS_snprintf(buf, sizeof(buf),
146 "%s:%i object at %p has negative ref count %i",
147 fname, lineno, op, op->ob_refcnt);
148 Py_FatalError(buf);
149}
150
151#endif /* Py_REF_DEBUG */
152
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000153PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000154PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000156 if (op == NULL)
157 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000158 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000160 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161 return op;
162}
163
Guido van Rossumb18618d2000-05-03 23:44:39 +0000164PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000165PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000166{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000167 if (op == NULL)
168 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000169 /* Any changes should be reflected in PyObject_INIT_VAR */
170 op->ob_size = size;
171 op->ob_type = tp;
172 _Py_NewReference((PyObject *)op);
173 return op;
174}
175
176PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000177_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000178{
179 PyObject *op;
180 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
181 if (op == NULL)
182 return PyErr_NoMemory();
183 return PyObject_INIT(op, tp);
184}
185
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000186PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000187_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000189 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000190 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000191 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000193 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000194 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000195}
196
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000197/* for binary compatibility with 2.2 */
198#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000199void
Fred Drake100814d2000-07-09 15:48:49 +0000200_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000201{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000202 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203}
204
Neal Norwitz1a997502003-01-13 20:13:12 +0000205/* Implementation of PyObject_Print with recursion checking */
206static int
207internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000208{
Guido van Rossum278ef591991-07-27 21:40:24 +0000209 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000210 if (nesting > 10) {
211 PyErr_SetString(PyExc_RuntimeError, "print recursion");
212 return -1;
213 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000215 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000216#ifdef USE_STACKCHECK
217 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000218 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000219 return -1;
220 }
221#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000222 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000223 if (op == NULL) {
224 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225 }
Guido van Rossum90933611991-06-07 16:10:43 +0000226 else {
227 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000228 fprintf(fp, "<refcnt %u at %p>",
229 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000230 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000231 PyObject *s;
232 if (flags & Py_PRINT_RAW)
233 s = PyObject_Str(op);
234 else
235 s = PyObject_Repr(op);
236 if (s == NULL)
237 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000238 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000239 ret = internal_print(s, fp, Py_PRINT_RAW,
240 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000241 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000242 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000243 }
Guido van Rossum90933611991-06-07 16:10:43 +0000244 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000245 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000246 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000247 if (ret == 0) {
248 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000249 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000250 clearerr(fp);
251 ret = -1;
252 }
253 }
254 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255}
256
Neal Norwitz1a997502003-01-13 20:13:12 +0000257int
258PyObject_Print(PyObject *op, FILE *fp, int flags)
259{
260 return internal_print(op, fp, flags, 0);
261}
262
263
Barry Warsaw9bf16442001-01-23 16:24:35 +0000264/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000265void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000266{
Barry Warsaweefb1072001-02-22 22:39:18 +0000267 if (op == NULL)
268 fprintf(stderr, "NULL\n");
269 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000270 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000271 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000272 fprintf(stderr, "\n"
273 "type : %s\n"
274 "refcount: %d\n"
275 "address : %p\n",
276 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
277 op->ob_refcnt,
278 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000279 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000280}
Barry Warsaw903138f2001-01-23 16:33:18 +0000281
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000283PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000285 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000286 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000287#ifdef USE_STACKCHECK
288 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000289 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000290 return NULL;
291 }
292#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000293 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000295 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000296 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000297 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000298 else {
299 PyObject *res;
300 res = (*v->ob_type->tp_repr)(v);
301 if (res == NULL)
302 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000303#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000304 if (PyUnicode_Check(res)) {
305 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000306 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000307 Py_DECREF(res);
308 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000309 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000310 else
311 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000312 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000313#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000314 if (!PyString_Check(res)) {
315 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000316 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000317 res->ob_type->tp_name);
318 Py_DECREF(res);
319 return NULL;
320 }
321 return res;
322 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000323}
324
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000325PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000326PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000327{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000328 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000329
Guido van Rossumc6004111993-11-05 10:22:19 +0000330 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000331 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000332 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000334 return v;
335 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000336 if (v->ob_type->tp_str == NULL)
337 return PyObject_Repr(v);
338
339 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000340 if (res == NULL)
341 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000342#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000343 if (PyUnicode_Check(res)) {
344 PyObject* str;
345 str = PyUnicode_AsEncodedString(res, NULL, NULL);
346 Py_DECREF(res);
347 if (str)
348 res = str;
349 else
350 return NULL;
351 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000352#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000353 if (!PyString_Check(res)) {
354 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000355 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000356 res->ob_type->tp_name);
357 Py_DECREF(res);
358 return NULL;
359 }
360 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000361}
362
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000363#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000364PyObject *
365PyObject_Unicode(PyObject *v)
366{
367 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000368
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000369 if (v == NULL)
370 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000371 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000372 Py_INCREF(v);
373 return v;
374 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000375 if (PyUnicode_Check(v)) {
376 /* For a Unicode subtype that's not a Unicode object,
377 return a true Unicode object with the same data. */
378 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
379 PyUnicode_GET_SIZE(v));
380 }
381 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000382 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000383 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000384 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000385 else {
386 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000387 static PyObject *unicodestr;
388 /* XXX As soon as we have a tp_unicode slot, we should
389 check this before trying the __unicode__
390 method. */
391 if (unicodestr == NULL) {
392 unicodestr= PyString_InternFromString(
393 "__unicode__");
394 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000395 return NULL;
396 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000397 func = PyObject_GetAttr(v, unicodestr);
398 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000399 res = PyEval_CallObject(func, (PyObject *)NULL);
400 Py_DECREF(func);
401 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000402 else {
403 PyErr_Clear();
404 if (v->ob_type->tp_str != NULL)
405 res = (*v->ob_type->tp_str)(v);
406 else
407 res = PyObject_Repr(v);
408 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000409 }
410 if (res == NULL)
411 return NULL;
412 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000413 PyObject *str;
414 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000415 Py_DECREF(res);
416 if (str)
417 res = str;
418 else
419 return NULL;
420 }
421 return res;
422}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000423#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000424
425
Guido van Rossuma4073002002-05-31 20:03:54 +0000426/* Helper to warn about deprecated tp_compare return values. Return:
427 -2 for an exception;
428 -1 if v < w;
429 0 if v == w;
430 1 if v > w.
431 (This function cannot return 2.)
432*/
433static int
434adjust_tp_compare(int c)
435{
436 if (PyErr_Occurred()) {
437 if (c != -1 && c != -2) {
438 PyObject *t, *v, *tb;
439 PyErr_Fetch(&t, &v, &tb);
440 if (PyErr_Warn(PyExc_RuntimeWarning,
441 "tp_compare didn't return -1 or -2 "
442 "for exception") < 0) {
443 Py_XDECREF(t);
444 Py_XDECREF(v);
445 Py_XDECREF(tb);
446 }
447 else
448 PyErr_Restore(t, v, tb);
449 }
450 return -2;
451 }
452 else if (c < -1 || c > 1) {
453 if (PyErr_Warn(PyExc_RuntimeWarning,
454 "tp_compare didn't return -1, 0 or 1") < 0)
455 return -2;
456 else
457 return c < -1 ? -1 : 1;
458 }
459 else {
460 assert(c >= -1 && c <= 1);
461 return c;
462 }
463}
464
465
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000466/* Macro to get the tp_richcompare field of a type if defined */
467#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
468 ? (t)->tp_richcompare : NULL)
469
Guido van Rossume797ec12001-01-17 15:24:28 +0000470/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
471static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000472
Guido van Rossume797ec12001-01-17 15:24:28 +0000473/* Try a genuine rich comparison, returning an object. Return:
474 NULL for exception;
475 NotImplemented if this particular rich comparison is not implemented or
476 undefined;
477 some object not equal to NotImplemented if it is implemented
478 (this latter object may not be a Boolean).
479*/
480static PyObject *
481try_rich_compare(PyObject *v, PyObject *w, int op)
482{
483 richcmpfunc f;
484 PyObject *res;
485
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000486 if (v->ob_type != w->ob_type &&
487 PyType_IsSubtype(w->ob_type, v->ob_type) &&
488 (f = RICHCOMPARE(w->ob_type)) != NULL) {
489 res = (*f)(w, v, swapped_op[op]);
490 if (res != Py_NotImplemented)
491 return res;
492 Py_DECREF(res);
493 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000494 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000495 res = (*f)(v, w, op);
496 if (res != Py_NotImplemented)
497 return res;
498 Py_DECREF(res);
499 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000500 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000501 return (*f)(w, v, swapped_op[op]);
502 }
503 res = Py_NotImplemented;
504 Py_INCREF(res);
505 return res;
506}
507
508/* Try a genuine rich comparison, returning an int. Return:
509 -1 for exception (including the case where try_rich_compare() returns an
510 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000511 0 if the outcome is false;
512 1 if the outcome is true;
513 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000514*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000515static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000516try_rich_compare_bool(PyObject *v, PyObject *w, int op)
517{
518 PyObject *res;
519 int ok;
520
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000521 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000522 return 2; /* Shortcut, avoid INCREF+DECREF */
523 res = try_rich_compare(v, w, op);
524 if (res == NULL)
525 return -1;
526 if (res == Py_NotImplemented) {
527 Py_DECREF(res);
528 return 2;
529 }
530 ok = PyObject_IsTrue(res);
531 Py_DECREF(res);
532 return ok;
533}
534
535/* Try rich comparisons to determine a 3-way comparison. Return:
536 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000537 -1 if v < w;
538 0 if v == w;
539 1 if v > w;
540 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000541*/
542static int
543try_rich_to_3way_compare(PyObject *v, PyObject *w)
544{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000545 static struct { int op; int outcome; } tries[3] = {
546 /* Try this operator, and if it is true, use this outcome: */
547 {Py_EQ, 0},
548 {Py_LT, -1},
549 {Py_GT, 1},
550 };
551 int i;
552
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000553 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000554 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000555
556 for (i = 0; i < 3; i++) {
557 switch (try_rich_compare_bool(v, w, tries[i].op)) {
558 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000559 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000560 case 1:
561 return tries[i].outcome;
562 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000563 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000564
565 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000566}
567
568/* Try a 3-way comparison, returning an int. Return:
569 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000570 -1 if v < w;
571 0 if v == w;
572 1 if v > w;
573 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000574*/
575static int
576try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000577{
578 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000579 cmpfunc f;
580
581 /* Comparisons involving instances are given to instance_compare,
582 which has the same return conventions as this function. */
583
Guido van Rossumab3b0342001-09-18 20:38:53 +0000584 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000585 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000586 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000587 if (PyInstance_Check(w))
588 return (*w->ob_type->tp_compare)(v, w);
589
Guido van Rossumab3b0342001-09-18 20:38:53 +0000590 /* If both have the same (non-NULL) tp_compare, use it. */
591 if (f != NULL && f == w->ob_type->tp_compare) {
592 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000593 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000594 }
595
596 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
597 if (f == _PyObject_SlotCompare ||
598 w->ob_type->tp_compare == _PyObject_SlotCompare)
599 return _PyObject_SlotCompare(v, w);
600
Guido van Rossume797ec12001-01-17 15:24:28 +0000601 /* Try coercion; if it fails, give up */
602 c = PyNumber_CoerceEx(&v, &w);
603 if (c < 0)
604 return -2;
605 if (c > 0)
606 return 2;
607
608 /* Try v's comparison, if defined */
609 if ((f = v->ob_type->tp_compare) != NULL) {
610 c = (*f)(v, w);
611 Py_DECREF(v);
612 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000613 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000614 }
615
616 /* Try w's comparison, if defined */
617 if ((f = w->ob_type->tp_compare) != NULL) {
618 c = (*f)(w, v); /* swapped! */
619 Py_DECREF(v);
620 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000621 c = adjust_tp_compare(c);
622 if (c >= -1)
623 return -c; /* Swapped! */
624 else
625 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000626 }
627
628 /* No comparison defined */
629 Py_DECREF(v);
630 Py_DECREF(w);
631 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000632}
633
Guido van Rossume797ec12001-01-17 15:24:28 +0000634/* Final fallback 3-way comparison, returning an int. Return:
635 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000636 -1 if v < w;
637 0 if v == w;
638 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000639*/
640static int
641default_3way_compare(PyObject *v, PyObject *w)
642{
643 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000644 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000645
646 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000647 /* When comparing these pointers, they must be cast to
648 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
649 * uintptr_t). ANSI specifies that pointer compares other
650 * than == and != to non-related structures are undefined.
651 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000652 Py_uintptr_t vv = (Py_uintptr_t)v;
653 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000654 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
655 }
656
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000657#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000658 /* Special case for Unicode */
659 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
660 c = PyUnicode_Compare(v, w);
661 if (!PyErr_Occurred())
662 return c;
663 /* TypeErrors are ignored: if Unicode coercion fails due
664 to one of the arguments not having the right type, we
665 continue as defined by the coercion protocol (see
666 above). Luckily, decoding errors are reported as
667 ValueErrors and are not masked by this technique. */
668 if (!PyErr_ExceptionMatches(PyExc_TypeError))
669 return -2;
670 PyErr_Clear();
671 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000672#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000673
Guido van Rossum0871e932001-01-22 19:28:09 +0000674 /* None is smaller than anything */
675 if (v == Py_None)
676 return -1;
677 if (w == Py_None)
678 return 1;
679
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000680 /* different type: compare type names; numbers are smaller */
681 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000682 vname = "";
683 else
684 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000685 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000686 wname = "";
687 else
688 wname = w->ob_type->tp_name;
689 c = strcmp(vname, wname);
690 if (c < 0)
691 return -1;
692 if (c > 0)
693 return 1;
694 /* Same type name, or (more likely) incomparable numeric types */
695 return ((Py_uintptr_t)(v->ob_type) < (
696 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000697}
698
699#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
700
Tim Peters6d60b2e2001-05-07 20:53:51 +0000701/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000702 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000703 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000704 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000705 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000706 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000707 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000708*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000709static int
Fred Drake100814d2000-07-09 15:48:49 +0000710do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000711{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000712 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000713 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000714
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000715 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000716 && (f = v->ob_type->tp_compare) != NULL) {
717 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000718 if (PyInstance_Check(v)) {
719 /* Instance tp_compare has a different signature.
720 But if it returns undefined we fall through. */
721 if (c != 2)
722 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000723 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000724 }
725 else
726 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000727 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000728 /* We only get here if one of the following is true:
729 a) v and w have different types
730 b) v and w have the same type, which doesn't have tp_compare
731 c) v and w are instances, and either __cmp__ is not defined or
732 __cmp__ returns NotImplemented
733 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000734 c = try_rich_to_3way_compare(v, w);
735 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000736 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000737 c = try_3way_compare(v, w);
738 if (c < 2)
739 return c;
740 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000741}
742
Tim Petersc99213f2001-11-04 05:57:16 +0000743/* Compare v to w. Return
744 -1 if v < w or exception (PyErr_Occurred() true in latter case).
745 0 if v == w.
746 1 if v > w.
747 XXX The docs (C API manual) say the return value is undefined in case
748 XXX of error.
749*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000750int
Fred Drake100814d2000-07-09 15:48:49 +0000751PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000752{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000753 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000754 int result;
755
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000756 if (v == NULL || w == NULL) {
757 PyErr_BadInternalCall();
758 return -1;
759 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760 if (v == w)
761 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000762 vtp = v->ob_type;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000763 if (Py_EnterRecursiveCall(" in cmp"))
764 return -1;
765 result = do_cmp(v, w);
766 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000767 return result < 0 ? -1 : result;
768}
769
Tim Petersc99213f2001-11-04 05:57:16 +0000770/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000771static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000772convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000773{
Guido van Rossume797ec12001-01-17 15:24:28 +0000774 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000775 switch (op) {
776 case Py_LT: c = c < 0; break;
777 case Py_LE: c = c <= 0; break;
778 case Py_EQ: c = c == 0; break;
779 case Py_NE: c = c != 0; break;
780 case Py_GT: c = c > 0; break;
781 case Py_GE: c = c >= 0; break;
782 }
783 result = c ? Py_True : Py_False;
784 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000785 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786}
Tim Peters803526b2002-07-07 05:13:56 +0000787
Tim Petersc99213f2001-11-04 05:57:16 +0000788/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
789 Return
790 NULL if error
791 Py_True if v op w
792 Py_False if not (v op w)
793*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000794static PyObject *
795try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
796{
797 int c;
798
799 c = try_3way_compare(v, w);
800 if (c >= 2)
801 c = default_3way_compare(v, w);
802 if (c <= -2)
803 return NULL;
804 return convert_3way_to_object(op, c);
805}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806
Tim Petersc99213f2001-11-04 05:57:16 +0000807/* Do rich comparison on v and w. Return
808 NULL if error
809 Else a new reference to an object other than Py_NotImplemented, usually(?):
810 Py_True if v op w
811 Py_False if not (v op w)
812*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000813static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000814do_richcmp(PyObject *v, PyObject *w, int op)
815{
816 PyObject *res;
817
818 res = try_rich_compare(v, w, op);
819 if (res != Py_NotImplemented)
820 return res;
821 Py_DECREF(res);
822
823 return try_3way_to_rich_compare(v, w, op);
824}
825
Tim Petersc99213f2001-11-04 05:57:16 +0000826/* Return:
827 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000828 some object not equal to NotImplemented if it is implemented
829 (this latter object may not be a Boolean).
830*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000831PyObject *
832PyObject_RichCompare(PyObject *v, PyObject *w, int op)
833{
834 PyObject *res;
835
836 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000837 if (Py_EnterRecursiveCall(" in cmp"))
838 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000839
Armin Rigo2b3eb402003-10-28 12:05:48 +0000840 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000841 get out cheap (don't bother with coercions etc.). */
842 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
843 cmpfunc fcmp;
844 richcmpfunc frich = RICHCOMPARE(v->ob_type);
845 /* If the type has richcmp, try it first. try_rich_compare
846 tries it two-sided, which is not needed since we've a
847 single type only. */
848 if (frich != NULL) {
849 res = (*frich)(v, w, op);
850 if (res != Py_NotImplemented)
851 goto Done;
852 Py_DECREF(res);
853 }
854 /* No richcmp, or this particular richmp not implemented.
855 Try 3-way cmp. */
856 fcmp = v->ob_type->tp_compare;
857 if (fcmp != NULL) {
858 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000859 c = adjust_tp_compare(c);
860 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000861 res = NULL;
862 goto Done;
863 }
864 res = convert_3way_to_object(op, c);
865 goto Done;
866 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000867 }
Tim Peters67754e92001-11-04 07:29:31 +0000868
869 /* Fast path not taken, or couldn't deliver a useful result. */
870 res = do_richcmp(v, w, op);
871Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000872 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000873 return res;
874}
875
Tim Petersde9725f2001-05-05 10:06:17 +0000876/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000877int
878PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
879{
880 PyObject *res = PyObject_RichCompare(v, w, op);
881 int ok;
882
883 if (res == NULL)
884 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000885 if (PyBool_Check(res))
886 ok = (res == Py_True);
887 else
888 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000889 Py_DECREF(res);
890 return ok;
891}
Fred Drake13634cf2000-06-29 19:17:04 +0000892
893/* Set of hash utility functions to help maintaining the invariant that
894 iff a==b then hash(a)==hash(b)
895
896 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
897*/
898
899long
Fred Drake100814d2000-07-09 15:48:49 +0000900_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000901{
Tim Peters39dce292000-08-15 03:34:48 +0000902 double intpart, fractpart;
903 int expo;
904 long hipart;
905 long x; /* the final hash value */
906 /* This is designed so that Python numbers of different types
907 * that compare equal hash to the same value; otherwise comparisons
908 * of mapping keys will turn out weird.
909 */
910
Tim Peters39dce292000-08-15 03:34:48 +0000911 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000912 if (fractpart == 0.0) {
913 /* This must return the same hash as an equal int or long. */
914 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
915 /* Convert to long and use its hash. */
916 PyObject *plong; /* converted to Python long */
917 if (Py_IS_INFINITY(intpart))
918 /* can't convert to long int -- arbitrary */
919 v = v < 0 ? -271828.0 : 314159.0;
920 plong = PyLong_FromDouble(v);
921 if (plong == NULL)
922 return -1;
923 x = PyObject_Hash(plong);
924 Py_DECREF(plong);
925 return x;
926 }
927 /* Fits in a C long == a Python int, so is its own hash. */
928 x = (long)intpart;
929 if (x == -1)
930 x = -2;
931 return x;
932 }
933 /* The fractional part is non-zero, so we don't have to worry about
934 * making this match the hash of some other type.
935 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000936 * Since the VAX D double format has 56 mantissa bits, which is the
937 * most of any double format in use, each of these parts may have as
938 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000939 * So, assuming sizeof(long) >= 4, each part can be broken into two
940 * longs; frexp and multiplication are used to do that.
941 * Also, since the Cray double format has 15 exponent bits, which is
942 * the most of any double format in use, shifting the exponent field
943 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000944 */
Tim Peters39dce292000-08-15 03:34:48 +0000945 v = frexp(v, &expo);
946 v *= 2147483648.0; /* 2**31 */
947 hipart = (long)v; /* take the top 32 bits */
948 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
949 x = hipart + (long)v + (expo << 15);
950 if (x == -1)
951 x = -2;
952 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000953}
954
955long
Fred Drake100814d2000-07-09 15:48:49 +0000956_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000957{
958#if SIZEOF_LONG >= SIZEOF_VOID_P
959 return (long)p;
960#else
961 /* convert to a Python long and hash that */
962 PyObject* longobj;
963 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000964
Fred Drake13634cf2000-06-29 19:17:04 +0000965 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
966 x = -1;
967 goto finally;
968 }
969 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000970
Fred Drake13634cf2000-06-29 19:17:04 +0000971finally:
972 Py_XDECREF(longobj);
973 return x;
974#endif
975}
976
977
Guido van Rossum9bfef441993-03-29 10:43:31 +0000978long
Fred Drake100814d2000-07-09 15:48:49 +0000979PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000980{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000981 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000982 if (tp->tp_hash != NULL)
983 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000984 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000985 return _Py_HashPointer(v); /* Use address as hash value */
986 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000987 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000988 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000989 return -1;
990}
991
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000993PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000994{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000995 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000996
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000998 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000999 w = PyString_InternFromString(name);
1000 if (w == NULL)
1001 return NULL;
1002 res = PyObject_GetAttr(v, w);
1003 Py_XDECREF(w);
1004 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001005}
1006
1007int
Fred Drake100814d2000-07-09 15:48:49 +00001008PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001009{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001010 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001011 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001012 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001013 return 1;
1014 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001015 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001016 return 0;
1017}
1018
1019int
Fred Drake100814d2000-07-09 15:48:49 +00001020PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001021{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022 PyObject *s;
1023 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001024
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001026 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027 s = PyString_InternFromString(name);
1028 if (s == NULL)
1029 return -1;
1030 res = PyObject_SetAttr(v, s, w);
1031 Py_XDECREF(s);
1032 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001033}
1034
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001035PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001036PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001037{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038 PyTypeObject *tp = v->ob_type;
1039
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001040 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001041#ifdef Py_USING_UNICODE
1042 /* The Unicode to string conversion is done here because the
1043 existing tp_getattro slots expect a string object as name
1044 and we wouldn't want to break those. */
1045 if (PyUnicode_Check(name)) {
1046 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1047 if (name == NULL)
1048 return NULL;
1049 }
1050 else
1051#endif
1052 {
1053 PyErr_SetString(PyExc_TypeError,
1054 "attribute name must be string");
1055 return NULL;
1056 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001057 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001058 if (tp->tp_getattro != NULL)
1059 return (*tp->tp_getattro)(v, name);
1060 if (tp->tp_getattr != NULL)
1061 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1062 PyErr_Format(PyExc_AttributeError,
1063 "'%.50s' object has no attribute '%.400s'",
1064 tp->tp_name, PyString_AS_STRING(name));
1065 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001066}
1067
1068int
Fred Drake100814d2000-07-09 15:48:49 +00001069PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001070{
1071 PyObject *res = PyObject_GetAttr(v, name);
1072 if (res != NULL) {
1073 Py_DECREF(res);
1074 return 1;
1075 }
1076 PyErr_Clear();
1077 return 0;
1078}
1079
1080int
Fred Drake100814d2000-07-09 15:48:49 +00001081PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001082{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001084 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001085
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001086 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001087#ifdef Py_USING_UNICODE
1088 /* The Unicode to string conversion is done here because the
1089 existing tp_setattro slots expect a string object as name
1090 and we wouldn't want to break those. */
1091 if (PyUnicode_Check(name)) {
1092 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1093 if (name == NULL)
1094 return -1;
1095 }
Tim Peters803526b2002-07-07 05:13:56 +00001096 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001097#endif
1098 {
1099 PyErr_SetString(PyExc_TypeError,
1100 "attribute name must be string");
1101 return -1;
1102 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001103 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001104 else
1105 Py_INCREF(name);
1106
1107 PyString_InternInPlace(&name);
1108 if (tp->tp_setattro != NULL) {
1109 err = (*tp->tp_setattro)(v, name, value);
1110 Py_DECREF(name);
1111 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 if (tp->tp_setattr != NULL) {
1114 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1115 Py_DECREF(name);
1116 return err;
1117 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001118 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1120 PyErr_Format(PyExc_TypeError,
1121 "'%.100s' object has no attributes "
1122 "(%s .%.100s)",
1123 tp->tp_name,
1124 value==NULL ? "del" : "assign to",
1125 PyString_AS_STRING(name));
1126 else
1127 PyErr_Format(PyExc_TypeError,
1128 "'%.100s' object has only read-only attributes "
1129 "(%s .%.100s)",
1130 tp->tp_name,
1131 value==NULL ? "del" : "assign to",
1132 PyString_AS_STRING(name));
1133 return -1;
1134}
1135
1136/* Helper to get a pointer to an object's __dict__ slot, if any */
1137
1138PyObject **
1139_PyObject_GetDictPtr(PyObject *obj)
1140{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141 long dictoffset;
1142 PyTypeObject *tp = obj->ob_type;
1143
1144 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1145 return NULL;
1146 dictoffset = tp->tp_dictoffset;
1147 if (dictoffset == 0)
1148 return NULL;
1149 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001150 int tsize;
1151 size_t size;
1152
1153 tsize = ((PyVarObject *)obj)->ob_size;
1154 if (tsize < 0)
1155 tsize = -tsize;
1156 size = _PyObject_VAR_SIZE(tp, tsize);
1157
Tim Peters6d483d32001-10-06 21:27:34 +00001158 dictoffset += (long)size;
1159 assert(dictoffset > 0);
1160 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001161 }
1162 return (PyObject **) ((char *)obj + dictoffset);
1163}
1164
1165/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1166
1167PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001168PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001169{
1170 Py_INCREF(obj);
1171 return obj;
1172}
1173
1174PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1176{
1177 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001178 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001179 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001181 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 PyObject **dictptr;
1183
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001184 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001185#ifdef Py_USING_UNICODE
1186 /* The Unicode to string conversion is done here because the
1187 existing tp_setattro slots expect a string object as name
1188 and we wouldn't want to break those. */
1189 if (PyUnicode_Check(name)) {
1190 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1191 if (name == NULL)
1192 return NULL;
1193 }
Tim Peters803526b2002-07-07 05:13:56 +00001194 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001195#endif
1196 {
1197 PyErr_SetString(PyExc_TypeError,
1198 "attribute name must be string");
1199 return NULL;
1200 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001201 }
1202 else
1203 Py_INCREF(name);
1204
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001206 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001207 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 }
1209
Guido van Rossum056fbf42002-08-19 19:22:50 +00001210 /* Inline _PyType_Lookup */
1211 {
1212 int i, n;
1213 PyObject *mro, *base, *dict;
1214
1215 /* Look in tp_dict of types in MRO */
1216 mro = tp->tp_mro;
1217 assert(mro != NULL);
1218 assert(PyTuple_Check(mro));
1219 n = PyTuple_GET_SIZE(mro);
1220 for (i = 0; i < n; i++) {
1221 base = PyTuple_GET_ITEM(mro, i);
1222 if (PyClass_Check(base))
1223 dict = ((PyClassObject *)base)->cl_dict;
1224 else {
1225 assert(PyType_Check(base));
1226 dict = ((PyTypeObject *)base)->tp_dict;
1227 }
1228 assert(dict && PyDict_Check(dict));
1229 descr = PyDict_GetItem(dict, name);
1230 if (descr != NULL)
1231 break;
1232 }
1233 }
1234
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001235 Py_XINCREF(descr);
1236
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001238 if (descr != NULL &&
1239 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001241 if (f != NULL && PyDescr_IsData(descr)) {
1242 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001243 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001244 goto done;
1245 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 }
1247
Guido van Rossumc66ff442002-08-19 16:50:48 +00001248 /* Inline _PyObject_GetDictPtr */
1249 dictoffset = tp->tp_dictoffset;
1250 if (dictoffset != 0) {
1251 PyObject *dict;
1252 if (dictoffset < 0) {
1253 int tsize;
1254 size_t size;
1255
1256 tsize = ((PyVarObject *)obj)->ob_size;
1257 if (tsize < 0)
1258 tsize = -tsize;
1259 size = _PyObject_VAR_SIZE(tp, tsize);
1260
1261 dictoffset += (long)size;
1262 assert(dictoffset > 0);
1263 assert(dictoffset % SIZEOF_VOID_P == 0);
1264 }
1265 dictptr = (PyObject **) ((char *)obj + dictoffset);
1266 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001268 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001269 if (res != NULL) {
1270 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001271 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001272 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 }
1274 }
1275 }
1276
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001277 if (f != NULL) {
1278 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001279 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001280 goto done;
1281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282
1283 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001284 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001285 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001286 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001287 }
1288
1289 PyErr_Format(PyExc_AttributeError,
1290 "'%.50s' object has no attribute '%.400s'",
1291 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001292 done:
1293 Py_DECREF(name);
1294 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295}
1296
1297int
1298PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1299{
1300 PyTypeObject *tp = obj->ob_type;
1301 PyObject *descr;
1302 descrsetfunc f;
1303 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001304 int res = -1;
1305
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001306 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001307#ifdef Py_USING_UNICODE
1308 /* The Unicode to string conversion is done here because the
1309 existing tp_setattro slots expect a string object as name
1310 and we wouldn't want to break those. */
1311 if (PyUnicode_Check(name)) {
1312 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1313 if (name == NULL)
1314 return -1;
1315 }
Tim Peters803526b2002-07-07 05:13:56 +00001316 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001317#endif
1318 {
1319 PyErr_SetString(PyExc_TypeError,
1320 "attribute name must be string");
1321 return -1;
1322 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001323 }
1324 else
1325 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326
1327 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001328 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001329 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 }
1331
1332 descr = _PyType_Lookup(tp, name);
1333 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001334 if (descr != NULL &&
1335 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001337 if (f != NULL && PyDescr_IsData(descr)) {
1338 res = f(descr, obj, value);
1339 goto done;
1340 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341 }
1342
1343 dictptr = _PyObject_GetDictPtr(obj);
1344 if (dictptr != NULL) {
1345 PyObject *dict = *dictptr;
1346 if (dict == NULL && value != NULL) {
1347 dict = PyDict_New();
1348 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001349 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350 *dictptr = dict;
1351 }
1352 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001353 if (value == NULL)
1354 res = PyDict_DelItem(dict, name);
1355 else
1356 res = PyDict_SetItem(dict, name, value);
1357 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1358 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360 }
1361 }
1362
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001363 if (f != NULL) {
1364 res = f(descr, obj, value);
1365 goto done;
1366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367
1368 if (descr == NULL) {
1369 PyErr_Format(PyExc_AttributeError,
1370 "'%.50s' object has no attribute '%.400s'",
1371 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001372 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 }
1374
1375 PyErr_Format(PyExc_AttributeError,
1376 "'%.50s' object attribute '%.400s' is read-only",
1377 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001378 done:
1379 Py_DECREF(name);
1380 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001381}
1382
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001383/* Test a value used as condition, e.g., in a for or if statement.
1384 Return -1 if an error occurred */
1385
1386int
Fred Drake100814d2000-07-09 15:48:49 +00001387PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001388{
1389 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001390 if (v == Py_True)
1391 return 1;
1392 if (v == Py_False)
1393 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001394 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001395 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001396 else if (v->ob_type->tp_as_number != NULL &&
1397 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001398 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001399 else if (v->ob_type->tp_as_mapping != NULL &&
1400 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001401 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001402 else if (v->ob_type->tp_as_sequence != NULL &&
1403 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001404 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1405 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001406 return 1;
1407 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001408}
1409
Tim Peters803526b2002-07-07 05:13:56 +00001410/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001411 Return -1 if an error occurred */
1412
1413int
Fred Drake100814d2000-07-09 15:48:49 +00001414PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001415{
1416 int res;
1417 res = PyObject_IsTrue(v);
1418 if (res < 0)
1419 return res;
1420 return res == 0;
1421}
1422
Guido van Rossum5524a591995-01-10 15:26:20 +00001423/* Coerce two numeric types to the "larger" one.
1424 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001425 Return value:
1426 -1 if an error occurred;
1427 0 if the coercion succeeded (and then the reference counts are increased);
1428 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001429*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001430int
Fred Drake100814d2000-07-09 15:48:49 +00001431PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001432{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001433 register PyObject *v = *pv;
1434 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001435 int res;
1436
Guido van Rossum517c7d42002-04-26 02:49:14 +00001437 /* Shortcut only for old-style types */
1438 if (v->ob_type == w->ob_type &&
1439 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1440 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441 Py_INCREF(v);
1442 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001443 return 0;
1444 }
1445 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1446 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1447 if (res <= 0)
1448 return res;
1449 }
1450 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1451 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1452 if (res <= 0)
1453 return res;
1454 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001455 return 1;
1456}
1457
Guido van Rossume797ec12001-01-17 15:24:28 +00001458/* Coerce two numeric types to the "larger" one.
1459 Increment the reference count on each argument.
1460 Return -1 and raise an exception if no coercion is possible
1461 (and then no reference count is incremented).
1462*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001463int
Fred Drake100814d2000-07-09 15:48:49 +00001464PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001465{
1466 int err = PyNumber_CoerceEx(pv, pw);
1467 if (err <= 0)
1468 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001469 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001470 return -1;
1471}
1472
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001473
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001474/* Test whether an object can be called */
1475
1476int
Fred Drake100814d2000-07-09 15:48:49 +00001477PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001478{
1479 if (x == NULL)
1480 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001481 if (PyInstance_Check(x)) {
1482 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001483 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001485 return 0;
1486 }
1487 /* Could test recursively but don't, for fear of endless
1488 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001490 return 1;
1491 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001492 else {
1493 return x->ob_type->tp_call != NULL;
1494 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001495}
1496
Tim Peters7eea37e2001-09-04 22:08:56 +00001497/* Helper for PyObject_Dir.
1498 Merge the __dict__ of aclass into dict, and recursively also all
1499 the __dict__s of aclass's base classes. The order of merging isn't
1500 defined, as it's expected that only the final set of dict keys is
1501 interesting.
1502 Return 0 on success, -1 on error.
1503*/
1504
1505static int
1506merge_class_dict(PyObject* dict, PyObject* aclass)
1507{
1508 PyObject *classdict;
1509 PyObject *bases;
1510
1511 assert(PyDict_Check(dict));
1512 assert(aclass);
1513
1514 /* Merge in the type's dict (if any). */
1515 classdict = PyObject_GetAttrString(aclass, "__dict__");
1516 if (classdict == NULL)
1517 PyErr_Clear();
1518 else {
1519 int status = PyDict_Update(dict, classdict);
1520 Py_DECREF(classdict);
1521 if (status < 0)
1522 return -1;
1523 }
1524
1525 /* Recursively merge in the base types' (if any) dicts. */
1526 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001527 if (bases == NULL)
1528 PyErr_Clear();
1529 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001530 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001531 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001532 n = PySequence_Size(bases); /* This better be right */
1533 if (n < 0)
1534 PyErr_Clear();
1535 else {
1536 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001537 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001538 PyObject *base = PySequence_GetItem(bases, i);
1539 if (base == NULL) {
1540 Py_DECREF(bases);
1541 return -1;
1542 }
Tim Peters18e70832003-02-05 19:35:19 +00001543 status = merge_class_dict(dict, base);
1544 Py_DECREF(base);
1545 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001546 Py_DECREF(bases);
1547 return -1;
1548 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001549 }
1550 }
1551 Py_DECREF(bases);
1552 }
1553 return 0;
1554}
1555
Tim Peters305b5852001-09-17 02:38:46 +00001556/* Helper for PyObject_Dir.
1557 If obj has an attr named attrname that's a list, merge its string
1558 elements into keys of dict.
1559 Return 0 on success, -1 on error. Errors due to not finding the attr,
1560 or the attr not being a list, are suppressed.
1561*/
1562
1563static int
1564merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1565{
1566 PyObject *list;
1567 int result = 0;
1568
1569 assert(PyDict_Check(dict));
1570 assert(obj);
1571 assert(attrname);
1572
1573 list = PyObject_GetAttrString(obj, attrname);
1574 if (list == NULL)
1575 PyErr_Clear();
1576
1577 else if (PyList_Check(list)) {
1578 int i;
1579 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1580 PyObject *item = PyList_GET_ITEM(list, i);
1581 if (PyString_Check(item)) {
1582 result = PyDict_SetItem(dict, item, Py_None);
1583 if (result < 0)
1584 break;
1585 }
1586 }
1587 }
1588
1589 Py_XDECREF(list);
1590 return result;
1591}
1592
Tim Peters7eea37e2001-09-04 22:08:56 +00001593/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1594 docstring, which should be kept in synch with this implementation. */
1595
1596PyObject *
1597PyObject_Dir(PyObject *arg)
1598{
1599 /* Set exactly one of these non-NULL before the end. */
1600 PyObject *result = NULL; /* result list */
1601 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1602
1603 /* If NULL arg, return the locals. */
1604 if (arg == NULL) {
1605 PyObject *locals = PyEval_GetLocals();
1606 if (locals == NULL)
1607 goto error;
1608 result = PyDict_Keys(locals);
1609 if (result == NULL)
1610 goto error;
1611 }
1612
1613 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001614 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001615 masterdict = PyObject_GetAttrString(arg, "__dict__");
1616 if (masterdict == NULL)
1617 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001618 if (!PyDict_Check(masterdict)) {
1619 PyErr_SetString(PyExc_TypeError,
1620 "module.__dict__ is not a dictionary");
1621 goto error;
1622 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001623 }
1624
1625 /* Elif some form of type or class, grab its dict and its bases.
1626 We deliberately don't suck up its __class__, as methods belonging
1627 to the metaclass would probably be more confusing than helpful. */
1628 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1629 masterdict = PyDict_New();
1630 if (masterdict == NULL)
1631 goto error;
1632 if (merge_class_dict(masterdict, arg) < 0)
1633 goto error;
1634 }
1635
1636 /* Else look at its dict, and the attrs reachable from its class. */
1637 else {
1638 PyObject *itsclass;
1639 /* Create a dict to start with. CAUTION: Not everything
1640 responding to __dict__ returns a dict! */
1641 masterdict = PyObject_GetAttrString(arg, "__dict__");
1642 if (masterdict == NULL) {
1643 PyErr_Clear();
1644 masterdict = PyDict_New();
1645 }
1646 else if (!PyDict_Check(masterdict)) {
1647 Py_DECREF(masterdict);
1648 masterdict = PyDict_New();
1649 }
1650 else {
1651 /* The object may have returned a reference to its
1652 dict, so copy it to avoid mutating it. */
1653 PyObject *temp = PyDict_Copy(masterdict);
1654 Py_DECREF(masterdict);
1655 masterdict = temp;
1656 }
1657 if (masterdict == NULL)
1658 goto error;
1659
Tim Peters305b5852001-09-17 02:38:46 +00001660 /* Merge in __members__ and __methods__ (if any).
1661 XXX Would like this to go away someday; for now, it's
1662 XXX needed to get at im_self etc of method objects. */
1663 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1664 goto error;
1665 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1666 goto error;
1667
Tim Peters7eea37e2001-09-04 22:08:56 +00001668 /* Merge in attrs reachable from its class.
1669 CAUTION: Not all objects have a __class__ attr. */
1670 itsclass = PyObject_GetAttrString(arg, "__class__");
1671 if (itsclass == NULL)
1672 PyErr_Clear();
1673 else {
1674 int status = merge_class_dict(masterdict, itsclass);
1675 Py_DECREF(itsclass);
1676 if (status < 0)
1677 goto error;
1678 }
1679 }
1680
1681 assert((result == NULL) ^ (masterdict == NULL));
1682 if (masterdict != NULL) {
1683 /* The result comes from its keys. */
1684 assert(result == NULL);
1685 result = PyDict_Keys(masterdict);
1686 if (result == NULL)
1687 goto error;
1688 }
1689
1690 assert(result);
1691 if (PyList_Sort(result) != 0)
1692 goto error;
1693 else
1694 goto normal_return;
1695
1696 error:
1697 Py_XDECREF(result);
1698 result = NULL;
1699 /* fall through */
1700 normal_return:
1701 Py_XDECREF(masterdict);
1702 return result;
1703}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001704
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001705/*
1706NoObject is usable as a non-NULL undefined value, used by the macro None.
1707There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001708so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001709(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001710*/
1711
Guido van Rossum0c182a11992-03-27 17:26:13 +00001712/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001713static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001714none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001715{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001716 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001717}
1718
Barry Warsaw9bf16442001-01-23 16:24:35 +00001719/* ARGUSED */
1720static void
Tim Peters803526b2002-07-07 05:13:56 +00001721none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001722{
1723 /* This should never get called, but we also don't want to SEGV if
1724 * we accidently decref None out of existance.
1725 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001726 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001727}
1728
1729
Guido van Rossumba21a492001-08-16 08:17:26 +00001730static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001731 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001732 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001733 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001734 0,
1735 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001736 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001737 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001738 0, /*tp_getattr*/
1739 0, /*tp_setattr*/
1740 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001741 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001742 0, /*tp_as_number*/
1743 0, /*tp_as_sequence*/
1744 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001745 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001746};
1747
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001748PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001749 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750};
1751
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001752/* NotImplemented is an object that can be used to signal that an
1753 operation is not implemented for the given type combination. */
1754
1755static PyObject *
1756NotImplemented_repr(PyObject *op)
1757{
1758 return PyString_FromString("NotImplemented");
1759}
1760
1761static PyTypeObject PyNotImplemented_Type = {
1762 PyObject_HEAD_INIT(&PyType_Type)
1763 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001764 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001765 0,
1766 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001767 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001768 0, /*tp_print*/
1769 0, /*tp_getattr*/
1770 0, /*tp_setattr*/
1771 0, /*tp_compare*/
1772 (reprfunc)NotImplemented_repr, /*tp_repr*/
1773 0, /*tp_as_number*/
1774 0, /*tp_as_sequence*/
1775 0, /*tp_as_mapping*/
1776 0, /*tp_hash */
1777};
1778
1779PyObject _Py_NotImplementedStruct = {
1780 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1781};
1782
Guido van Rossumba21a492001-08-16 08:17:26 +00001783void
1784_Py_ReadyTypes(void)
1785{
1786 if (PyType_Ready(&PyType_Type) < 0)
1787 Py_FatalError("Can't initialize 'type'");
1788
Guido van Rossum77f6a652002-04-03 22:41:51 +00001789 if (PyType_Ready(&PyBool_Type) < 0)
1790 Py_FatalError("Can't initialize 'bool'");
1791
Guido van Rossumcacfc072002-05-24 19:01:59 +00001792 if (PyType_Ready(&PyString_Type) < 0)
1793 Py_FatalError("Can't initialize 'str'");
1794
Guido van Rossumba21a492001-08-16 08:17:26 +00001795 if (PyType_Ready(&PyList_Type) < 0)
1796 Py_FatalError("Can't initialize 'list'");
1797
1798 if (PyType_Ready(&PyNone_Type) < 0)
1799 Py_FatalError("Can't initialize type(None)");
1800
1801 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1802 Py_FatalError("Can't initialize type(NotImplemented)");
1803}
1804
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001805
Guido van Rossum84a90321996-05-22 16:34:47 +00001806#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001807
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001808void
Fred Drake100814d2000-07-09 15:48:49 +00001809_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001810{
Tim Peters34592512002-07-11 06:23:50 +00001811 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001812 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001813 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001814 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001815}
1816
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001817void
Fred Drake100814d2000-07-09 15:48:49 +00001818_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001820#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001821 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001822#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001823 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001824 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001825 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001826 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001827 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001828#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001829 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1830 if (p == op)
1831 break;
1832 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001833 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001834 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001835#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001836 op->_ob_next->_ob_prev = op->_ob_prev;
1837 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001838 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001839 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001840}
1841
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001842void
Fred Drake100814d2000-07-09 15:48:49 +00001843_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001844{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001845 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001846 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001847 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001848}
1849
Tim Peters269b2a62003-04-17 19:52:29 +00001850/* Print all live objects. Because PyObject_Print is called, the
1851 * interpreter must be in a healthy state.
1852 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001853void
Fred Drake100814d2000-07-09 15:48:49 +00001854_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001855{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001856 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001857 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001859 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001860 if (PyObject_Print(op, fp, 0) != 0)
1861 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001862 putc('\n', fp);
1863 }
1864}
1865
Tim Peters269b2a62003-04-17 19:52:29 +00001866/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1867 * doesn't make any calls to the Python C API, so is always safe to call.
1868 */
1869void
1870_Py_PrintReferenceAddresses(FILE *fp)
1871{
1872 PyObject *op;
1873 fprintf(fp, "Remaining object addresses:\n");
1874 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001875 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1876 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001877}
1878
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001879PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001880_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001881{
1882 int i, n;
1883 PyObject *t = NULL;
1884 PyObject *res, *op;
1885
1886 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1887 return NULL;
1888 op = refchain._ob_next;
1889 res = PyList_New(0);
1890 if (res == NULL)
1891 return NULL;
1892 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1893 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001894 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001895 op = op->_ob_next;
1896 if (op == &refchain)
1897 return res;
1898 }
1899 if (PyList_Append(res, op) < 0) {
1900 Py_DECREF(res);
1901 return NULL;
1902 }
1903 op = op->_ob_next;
1904 }
1905 return res;
1906}
1907
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001908#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001909
1910
1911/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001912PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001913
1914
1915/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001916int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001917
1918
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001919/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001920
Thomas Wouters334fb892000-07-25 12:56:38 +00001921void *
Fred Drake100814d2000-07-09 15:48:49 +00001922PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001923{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001924 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001925}
1926
Thomas Wouters334fb892000-07-25 12:56:38 +00001927void *
1928PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001929{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001930 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001931}
1932
1933void
Thomas Wouters334fb892000-07-25 12:56:38 +00001934PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001935{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001936 PyMem_FREE(p);
1937}
1938
1939
Guido van Rossum86610361998-04-10 22:32:46 +00001940/* These methods are used to control infinite recursion in repr, str, print,
1941 etc. Container objects that may recursively contain themselves,
1942 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1943 Py_ReprLeave() to avoid infinite recursion.
1944
1945 Py_ReprEnter() returns 0 the first time it is called for a particular
1946 object and 1 every time thereafter. It returns -1 if an exception
1947 occurred. Py_ReprLeave() has no return value.
1948
1949 See dictobject.c and listobject.c for examples of use.
1950*/
1951
1952#define KEY "Py_Repr"
1953
1954int
Fred Drake100814d2000-07-09 15:48:49 +00001955Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001956{
1957 PyObject *dict;
1958 PyObject *list;
1959 int i;
1960
1961 dict = PyThreadState_GetDict();
1962 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001963 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001964 list = PyDict_GetItemString(dict, KEY);
1965 if (list == NULL) {
1966 list = PyList_New(0);
1967 if (list == NULL)
1968 return -1;
1969 if (PyDict_SetItemString(dict, KEY, list) < 0)
1970 return -1;
1971 Py_DECREF(list);
1972 }
1973 i = PyList_GET_SIZE(list);
1974 while (--i >= 0) {
1975 if (PyList_GET_ITEM(list, i) == obj)
1976 return 1;
1977 }
1978 PyList_Append(list, obj);
1979 return 0;
1980}
1981
1982void
Fred Drake100814d2000-07-09 15:48:49 +00001983Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001984{
1985 PyObject *dict;
1986 PyObject *list;
1987 int i;
1988
1989 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001990 if (dict == NULL)
1991 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001992 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001993 if (list == NULL || !PyList_Check(list))
1994 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001995 i = PyList_GET_SIZE(list);
1996 /* Count backwards because we always expect obj to be list[-1] */
1997 while (--i >= 0) {
1998 if (PyList_GET_ITEM(list, i) == obj) {
1999 PyList_SetSlice(list, i, i + 1, NULL);
2000 break;
2001 }
2002 }
2003}
Guido van Rossumd724b232000-03-13 16:01:29 +00002004
Tim Peters803526b2002-07-07 05:13:56 +00002005/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002006
Tim Peters803526b2002-07-07 05:13:56 +00002007/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002008int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002009
Tim Peters803526b2002-07-07 05:13:56 +00002010/* List of objects that still need to be cleaned up, singly linked via their
2011 * gc headers' gc_prev pointers.
2012 */
2013PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002014
Tim Peters803526b2002-07-07 05:13:56 +00002015/* Add op to the _PyTrash_delete_later list. Called when the current
2016 * call-stack depth gets large. op must be a currently untracked gc'ed
2017 * object, with refcount 0. Py_DECREF must already have been called on it.
2018 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002019void
Fred Drake100814d2000-07-09 15:48:49 +00002020_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002021{
Tim Peters803526b2002-07-07 05:13:56 +00002022 assert(PyObject_IS_GC(op));
2023 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2024 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002025 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002026 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002027}
2028
Tim Peters803526b2002-07-07 05:13:56 +00002029/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2030 * the call-stack unwinds again.
2031 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002032void
Fred Drake100814d2000-07-09 15:48:49 +00002033_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002034{
2035 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002036 PyObject *op = _PyTrash_delete_later;
2037 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002038
Neil Schemenauerf589c052002-03-29 03:05:54 +00002039 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002040 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002041
Tim Peters803526b2002-07-07 05:13:56 +00002042 /* Call the deallocator directly. This used to try to
2043 * fool Py_DECREF into calling it indirectly, but
2044 * Py_DECREF was already called on this object, and in
2045 * assorted non-release builds calling Py_DECREF again ends
2046 * up distorting allocation statistics.
2047 */
2048 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002049 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002050 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002051 --_PyTrash_delete_nesting;
2052 }
2053}