blob: d85f697fa4e4c3ccead499d84e775db6c39f0a14 [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
911#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
912{
913 extended e;
914 fractpart = modf(v, &e);
915 intpart = e;
916}
917#else
918 fractpart = modf(v, &intpart);
919#endif
920 if (fractpart == 0.0) {
921 /* This must return the same hash as an equal int or long. */
922 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
923 /* Convert to long and use its hash. */
924 PyObject *plong; /* converted to Python long */
925 if (Py_IS_INFINITY(intpart))
926 /* can't convert to long int -- arbitrary */
927 v = v < 0 ? -271828.0 : 314159.0;
928 plong = PyLong_FromDouble(v);
929 if (plong == NULL)
930 return -1;
931 x = PyObject_Hash(plong);
932 Py_DECREF(plong);
933 return x;
934 }
935 /* Fits in a C long == a Python int, so is its own hash. */
936 x = (long)intpart;
937 if (x == -1)
938 x = -2;
939 return x;
940 }
941 /* The fractional part is non-zero, so we don't have to worry about
942 * making this match the hash of some other type.
943 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000944 * Since the VAX D double format has 56 mantissa bits, which is the
945 * most of any double format in use, each of these parts may have as
946 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000947 * So, assuming sizeof(long) >= 4, each part can be broken into two
948 * longs; frexp and multiplication are used to do that.
949 * Also, since the Cray double format has 15 exponent bits, which is
950 * the most of any double format in use, shifting the exponent field
951 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000952 */
Tim Peters39dce292000-08-15 03:34:48 +0000953 v = frexp(v, &expo);
954 v *= 2147483648.0; /* 2**31 */
955 hipart = (long)v; /* take the top 32 bits */
956 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
957 x = hipart + (long)v + (expo << 15);
958 if (x == -1)
959 x = -2;
960 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000961}
962
963long
Fred Drake100814d2000-07-09 15:48:49 +0000964_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000965{
966#if SIZEOF_LONG >= SIZEOF_VOID_P
967 return (long)p;
968#else
969 /* convert to a Python long and hash that */
970 PyObject* longobj;
971 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000972
Fred Drake13634cf2000-06-29 19:17:04 +0000973 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
974 x = -1;
975 goto finally;
976 }
977 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000978
Fred Drake13634cf2000-06-29 19:17:04 +0000979finally:
980 Py_XDECREF(longobj);
981 return x;
982#endif
983}
984
985
Guido van Rossum9bfef441993-03-29 10:43:31 +0000986long
Fred Drake100814d2000-07-09 15:48:49 +0000987PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000988{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000990 if (tp->tp_hash != NULL)
991 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000992 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000993 return _Py_HashPointer(v); /* Use address as hash value */
994 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000995 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000996 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000997 return -1;
998}
999
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001000PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001001PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001002{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001004
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001006 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 w = PyString_InternFromString(name);
1008 if (w == NULL)
1009 return NULL;
1010 res = PyObject_GetAttr(v, w);
1011 Py_XDECREF(w);
1012 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001013}
1014
1015int
Fred Drake100814d2000-07-09 15:48:49 +00001016PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001017{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001018 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001019 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001020 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001021 return 1;
1022 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001023 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001024 return 0;
1025}
1026
1027int
Fred Drake100814d2000-07-09 15:48:49 +00001028PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001029{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030 PyObject *s;
1031 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001032
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001034 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 s = PyString_InternFromString(name);
1036 if (s == NULL)
1037 return -1;
1038 res = PyObject_SetAttr(v, s, w);
1039 Py_XDECREF(s);
1040 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001041}
1042
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001043PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001044PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001045{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046 PyTypeObject *tp = v->ob_type;
1047
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001048 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001049#ifdef Py_USING_UNICODE
1050 /* The Unicode to string conversion is done here because the
1051 existing tp_getattro slots expect a string object as name
1052 and we wouldn't want to break those. */
1053 if (PyUnicode_Check(name)) {
1054 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1055 if (name == NULL)
1056 return NULL;
1057 }
1058 else
1059#endif
1060 {
1061 PyErr_SetString(PyExc_TypeError,
1062 "attribute name must be string");
1063 return NULL;
1064 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001065 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 if (tp->tp_getattro != NULL)
1067 return (*tp->tp_getattro)(v, name);
1068 if (tp->tp_getattr != NULL)
1069 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1070 PyErr_Format(PyExc_AttributeError,
1071 "'%.50s' object has no attribute '%.400s'",
1072 tp->tp_name, PyString_AS_STRING(name));
1073 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001074}
1075
1076int
Fred Drake100814d2000-07-09 15:48:49 +00001077PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001078{
1079 PyObject *res = PyObject_GetAttr(v, name);
1080 if (res != NULL) {
1081 Py_DECREF(res);
1082 return 1;
1083 }
1084 PyErr_Clear();
1085 return 0;
1086}
1087
1088int
Fred Drake100814d2000-07-09 15:48:49 +00001089PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001090{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001092 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001093
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001094 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001095#ifdef Py_USING_UNICODE
1096 /* The Unicode to string conversion is done here because the
1097 existing tp_setattro slots expect a string object as name
1098 and we wouldn't want to break those. */
1099 if (PyUnicode_Check(name)) {
1100 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1101 if (name == NULL)
1102 return -1;
1103 }
Tim Peters803526b2002-07-07 05:13:56 +00001104 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001105#endif
1106 {
1107 PyErr_SetString(PyExc_TypeError,
1108 "attribute name must be string");
1109 return -1;
1110 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 else
1113 Py_INCREF(name);
1114
1115 PyString_InternInPlace(&name);
1116 if (tp->tp_setattro != NULL) {
1117 err = (*tp->tp_setattro)(v, name, value);
1118 Py_DECREF(name);
1119 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001120 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 if (tp->tp_setattr != NULL) {
1122 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1123 Py_DECREF(name);
1124 return err;
1125 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001126 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1128 PyErr_Format(PyExc_TypeError,
1129 "'%.100s' object has no attributes "
1130 "(%s .%.100s)",
1131 tp->tp_name,
1132 value==NULL ? "del" : "assign to",
1133 PyString_AS_STRING(name));
1134 else
1135 PyErr_Format(PyExc_TypeError,
1136 "'%.100s' object has only read-only attributes "
1137 "(%s .%.100s)",
1138 tp->tp_name,
1139 value==NULL ? "del" : "assign to",
1140 PyString_AS_STRING(name));
1141 return -1;
1142}
1143
1144/* Helper to get a pointer to an object's __dict__ slot, if any */
1145
1146PyObject **
1147_PyObject_GetDictPtr(PyObject *obj)
1148{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 long dictoffset;
1150 PyTypeObject *tp = obj->ob_type;
1151
1152 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1153 return NULL;
1154 dictoffset = tp->tp_dictoffset;
1155 if (dictoffset == 0)
1156 return NULL;
1157 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001158 int tsize;
1159 size_t size;
1160
1161 tsize = ((PyVarObject *)obj)->ob_size;
1162 if (tsize < 0)
1163 tsize = -tsize;
1164 size = _PyObject_VAR_SIZE(tp, tsize);
1165
Tim Peters6d483d32001-10-06 21:27:34 +00001166 dictoffset += (long)size;
1167 assert(dictoffset > 0);
1168 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 }
1170 return (PyObject **) ((char *)obj + dictoffset);
1171}
1172
1173/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1174
1175PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001176PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001177{
1178 Py_INCREF(obj);
1179 return obj;
1180}
1181
1182PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1184{
1185 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001186 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001187 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001189 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 PyObject **dictptr;
1191
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001192 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001193#ifdef Py_USING_UNICODE
1194 /* The Unicode to string conversion is done here because the
1195 existing tp_setattro slots expect a string object as name
1196 and we wouldn't want to break those. */
1197 if (PyUnicode_Check(name)) {
1198 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1199 if (name == NULL)
1200 return NULL;
1201 }
Tim Peters803526b2002-07-07 05:13:56 +00001202 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001203#endif
1204 {
1205 PyErr_SetString(PyExc_TypeError,
1206 "attribute name must be string");
1207 return NULL;
1208 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001209 }
1210 else
1211 Py_INCREF(name);
1212
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001214 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001215 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 }
1217
Guido van Rossum056fbf42002-08-19 19:22:50 +00001218 /* Inline _PyType_Lookup */
1219 {
1220 int i, n;
1221 PyObject *mro, *base, *dict;
1222
1223 /* Look in tp_dict of types in MRO */
1224 mro = tp->tp_mro;
1225 assert(mro != NULL);
1226 assert(PyTuple_Check(mro));
1227 n = PyTuple_GET_SIZE(mro);
1228 for (i = 0; i < n; i++) {
1229 base = PyTuple_GET_ITEM(mro, i);
1230 if (PyClass_Check(base))
1231 dict = ((PyClassObject *)base)->cl_dict;
1232 else {
1233 assert(PyType_Check(base));
1234 dict = ((PyTypeObject *)base)->tp_dict;
1235 }
1236 assert(dict && PyDict_Check(dict));
1237 descr = PyDict_GetItem(dict, name);
1238 if (descr != NULL)
1239 break;
1240 }
1241 }
1242
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001243 Py_XINCREF(descr);
1244
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001246 if (descr != NULL &&
1247 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001249 if (f != NULL && PyDescr_IsData(descr)) {
1250 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001251 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001252 goto done;
1253 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 }
1255
Guido van Rossumc66ff442002-08-19 16:50:48 +00001256 /* Inline _PyObject_GetDictPtr */
1257 dictoffset = tp->tp_dictoffset;
1258 if (dictoffset != 0) {
1259 PyObject *dict;
1260 if (dictoffset < 0) {
1261 int tsize;
1262 size_t size;
1263
1264 tsize = ((PyVarObject *)obj)->ob_size;
1265 if (tsize < 0)
1266 tsize = -tsize;
1267 size = _PyObject_VAR_SIZE(tp, tsize);
1268
1269 dictoffset += (long)size;
1270 assert(dictoffset > 0);
1271 assert(dictoffset % SIZEOF_VOID_P == 0);
1272 }
1273 dictptr = (PyObject **) ((char *)obj + dictoffset);
1274 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001276 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 if (res != NULL) {
1278 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001279 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001280 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281 }
1282 }
1283 }
1284
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001285 if (f != NULL) {
1286 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001287 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001288 goto done;
1289 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290
1291 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001292 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001293 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001294 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 }
1296
1297 PyErr_Format(PyExc_AttributeError,
1298 "'%.50s' object has no attribute '%.400s'",
1299 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001300 done:
1301 Py_DECREF(name);
1302 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303}
1304
1305int
1306PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1307{
1308 PyTypeObject *tp = obj->ob_type;
1309 PyObject *descr;
1310 descrsetfunc f;
1311 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001312 int res = -1;
1313
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001314 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001315#ifdef Py_USING_UNICODE
1316 /* The Unicode to string conversion is done here because the
1317 existing tp_setattro slots expect a string object as name
1318 and we wouldn't want to break those. */
1319 if (PyUnicode_Check(name)) {
1320 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1321 if (name == NULL)
1322 return -1;
1323 }
Tim Peters803526b2002-07-07 05:13:56 +00001324 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001325#endif
1326 {
1327 PyErr_SetString(PyExc_TypeError,
1328 "attribute name must be string");
1329 return -1;
1330 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001331 }
1332 else
1333 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334
1335 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001336 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001337 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 }
1339
1340 descr = _PyType_Lookup(tp, name);
1341 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001342 if (descr != NULL &&
1343 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001345 if (f != NULL && PyDescr_IsData(descr)) {
1346 res = f(descr, obj, value);
1347 goto done;
1348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 }
1350
1351 dictptr = _PyObject_GetDictPtr(obj);
1352 if (dictptr != NULL) {
1353 PyObject *dict = *dictptr;
1354 if (dict == NULL && value != NULL) {
1355 dict = PyDict_New();
1356 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001357 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358 *dictptr = dict;
1359 }
1360 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001361 if (value == NULL)
1362 res = PyDict_DelItem(dict, name);
1363 else
1364 res = PyDict_SetItem(dict, name, value);
1365 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1366 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001367 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368 }
1369 }
1370
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001371 if (f != NULL) {
1372 res = f(descr, obj, value);
1373 goto done;
1374 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375
1376 if (descr == NULL) {
1377 PyErr_Format(PyExc_AttributeError,
1378 "'%.50s' object has no attribute '%.400s'",
1379 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001380 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 }
1382
1383 PyErr_Format(PyExc_AttributeError,
1384 "'%.50s' object attribute '%.400s' is read-only",
1385 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001386 done:
1387 Py_DECREF(name);
1388 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001389}
1390
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001391/* Test a value used as condition, e.g., in a for or if statement.
1392 Return -1 if an error occurred */
1393
1394int
Fred Drake100814d2000-07-09 15:48:49 +00001395PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001396{
1397 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001398 if (v == Py_True)
1399 return 1;
1400 if (v == Py_False)
1401 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001402 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001403 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001404 else if (v->ob_type->tp_as_number != NULL &&
1405 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001406 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001407 else if (v->ob_type->tp_as_mapping != NULL &&
1408 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001409 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001410 else if (v->ob_type->tp_as_sequence != NULL &&
1411 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001412 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1413 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001414 return 1;
1415 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001416}
1417
Tim Peters803526b2002-07-07 05:13:56 +00001418/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001419 Return -1 if an error occurred */
1420
1421int
Fred Drake100814d2000-07-09 15:48:49 +00001422PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001423{
1424 int res;
1425 res = PyObject_IsTrue(v);
1426 if (res < 0)
1427 return res;
1428 return res == 0;
1429}
1430
Guido van Rossum5524a591995-01-10 15:26:20 +00001431/* Coerce two numeric types to the "larger" one.
1432 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001433 Return value:
1434 -1 if an error occurred;
1435 0 if the coercion succeeded (and then the reference counts are increased);
1436 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001437*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001438int
Fred Drake100814d2000-07-09 15:48:49 +00001439PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001440{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441 register PyObject *v = *pv;
1442 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001443 int res;
1444
Guido van Rossum517c7d42002-04-26 02:49:14 +00001445 /* Shortcut only for old-style types */
1446 if (v->ob_type == w->ob_type &&
1447 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1448 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001449 Py_INCREF(v);
1450 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001451 return 0;
1452 }
1453 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1454 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1455 if (res <= 0)
1456 return res;
1457 }
1458 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1459 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1460 if (res <= 0)
1461 return res;
1462 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001463 return 1;
1464}
1465
Guido van Rossume797ec12001-01-17 15:24:28 +00001466/* Coerce two numeric types to the "larger" one.
1467 Increment the reference count on each argument.
1468 Return -1 and raise an exception if no coercion is possible
1469 (and then no reference count is incremented).
1470*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001471int
Fred Drake100814d2000-07-09 15:48:49 +00001472PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001473{
1474 int err = PyNumber_CoerceEx(pv, pw);
1475 if (err <= 0)
1476 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001477 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001478 return -1;
1479}
1480
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001481
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001482/* Test whether an object can be called */
1483
1484int
Fred Drake100814d2000-07-09 15:48:49 +00001485PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001486{
1487 if (x == NULL)
1488 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 if (PyInstance_Check(x)) {
1490 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001491 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001492 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001493 return 0;
1494 }
1495 /* Could test recursively but don't, for fear of endless
1496 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001497 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001498 return 1;
1499 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500 else {
1501 return x->ob_type->tp_call != NULL;
1502 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001503}
1504
Tim Peters7eea37e2001-09-04 22:08:56 +00001505/* Helper for PyObject_Dir.
1506 Merge the __dict__ of aclass into dict, and recursively also all
1507 the __dict__s of aclass's base classes. The order of merging isn't
1508 defined, as it's expected that only the final set of dict keys is
1509 interesting.
1510 Return 0 on success, -1 on error.
1511*/
1512
1513static int
1514merge_class_dict(PyObject* dict, PyObject* aclass)
1515{
1516 PyObject *classdict;
1517 PyObject *bases;
1518
1519 assert(PyDict_Check(dict));
1520 assert(aclass);
1521
1522 /* Merge in the type's dict (if any). */
1523 classdict = PyObject_GetAttrString(aclass, "__dict__");
1524 if (classdict == NULL)
1525 PyErr_Clear();
1526 else {
1527 int status = PyDict_Update(dict, classdict);
1528 Py_DECREF(classdict);
1529 if (status < 0)
1530 return -1;
1531 }
1532
1533 /* Recursively merge in the base types' (if any) dicts. */
1534 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001535 if (bases == NULL)
1536 PyErr_Clear();
1537 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001538 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001539 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001540 n = PySequence_Size(bases); /* This better be right */
1541 if (n < 0)
1542 PyErr_Clear();
1543 else {
1544 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001545 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001546 PyObject *base = PySequence_GetItem(bases, i);
1547 if (base == NULL) {
1548 Py_DECREF(bases);
1549 return -1;
1550 }
Tim Peters18e70832003-02-05 19:35:19 +00001551 status = merge_class_dict(dict, base);
1552 Py_DECREF(base);
1553 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001554 Py_DECREF(bases);
1555 return -1;
1556 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001557 }
1558 }
1559 Py_DECREF(bases);
1560 }
1561 return 0;
1562}
1563
Tim Peters305b5852001-09-17 02:38:46 +00001564/* Helper for PyObject_Dir.
1565 If obj has an attr named attrname that's a list, merge its string
1566 elements into keys of dict.
1567 Return 0 on success, -1 on error. Errors due to not finding the attr,
1568 or the attr not being a list, are suppressed.
1569*/
1570
1571static int
1572merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1573{
1574 PyObject *list;
1575 int result = 0;
1576
1577 assert(PyDict_Check(dict));
1578 assert(obj);
1579 assert(attrname);
1580
1581 list = PyObject_GetAttrString(obj, attrname);
1582 if (list == NULL)
1583 PyErr_Clear();
1584
1585 else if (PyList_Check(list)) {
1586 int i;
1587 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1588 PyObject *item = PyList_GET_ITEM(list, i);
1589 if (PyString_Check(item)) {
1590 result = PyDict_SetItem(dict, item, Py_None);
1591 if (result < 0)
1592 break;
1593 }
1594 }
1595 }
1596
1597 Py_XDECREF(list);
1598 return result;
1599}
1600
Tim Peters7eea37e2001-09-04 22:08:56 +00001601/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1602 docstring, which should be kept in synch with this implementation. */
1603
1604PyObject *
1605PyObject_Dir(PyObject *arg)
1606{
1607 /* Set exactly one of these non-NULL before the end. */
1608 PyObject *result = NULL; /* result list */
1609 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1610
1611 /* If NULL arg, return the locals. */
1612 if (arg == NULL) {
1613 PyObject *locals = PyEval_GetLocals();
1614 if (locals == NULL)
1615 goto error;
1616 result = PyDict_Keys(locals);
1617 if (result == NULL)
1618 goto error;
1619 }
1620
1621 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001622 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001623 masterdict = PyObject_GetAttrString(arg, "__dict__");
1624 if (masterdict == NULL)
1625 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001626 if (!PyDict_Check(masterdict)) {
1627 PyErr_SetString(PyExc_TypeError,
1628 "module.__dict__ is not a dictionary");
1629 goto error;
1630 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001631 }
1632
1633 /* Elif some form of type or class, grab its dict and its bases.
1634 We deliberately don't suck up its __class__, as methods belonging
1635 to the metaclass would probably be more confusing than helpful. */
1636 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1637 masterdict = PyDict_New();
1638 if (masterdict == NULL)
1639 goto error;
1640 if (merge_class_dict(masterdict, arg) < 0)
1641 goto error;
1642 }
1643
1644 /* Else look at its dict, and the attrs reachable from its class. */
1645 else {
1646 PyObject *itsclass;
1647 /* Create a dict to start with. CAUTION: Not everything
1648 responding to __dict__ returns a dict! */
1649 masterdict = PyObject_GetAttrString(arg, "__dict__");
1650 if (masterdict == NULL) {
1651 PyErr_Clear();
1652 masterdict = PyDict_New();
1653 }
1654 else if (!PyDict_Check(masterdict)) {
1655 Py_DECREF(masterdict);
1656 masterdict = PyDict_New();
1657 }
1658 else {
1659 /* The object may have returned a reference to its
1660 dict, so copy it to avoid mutating it. */
1661 PyObject *temp = PyDict_Copy(masterdict);
1662 Py_DECREF(masterdict);
1663 masterdict = temp;
1664 }
1665 if (masterdict == NULL)
1666 goto error;
1667
Tim Peters305b5852001-09-17 02:38:46 +00001668 /* Merge in __members__ and __methods__ (if any).
1669 XXX Would like this to go away someday; for now, it's
1670 XXX needed to get at im_self etc of method objects. */
1671 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1672 goto error;
1673 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1674 goto error;
1675
Tim Peters7eea37e2001-09-04 22:08:56 +00001676 /* Merge in attrs reachable from its class.
1677 CAUTION: Not all objects have a __class__ attr. */
1678 itsclass = PyObject_GetAttrString(arg, "__class__");
1679 if (itsclass == NULL)
1680 PyErr_Clear();
1681 else {
1682 int status = merge_class_dict(masterdict, itsclass);
1683 Py_DECREF(itsclass);
1684 if (status < 0)
1685 goto error;
1686 }
1687 }
1688
1689 assert((result == NULL) ^ (masterdict == NULL));
1690 if (masterdict != NULL) {
1691 /* The result comes from its keys. */
1692 assert(result == NULL);
1693 result = PyDict_Keys(masterdict);
1694 if (result == NULL)
1695 goto error;
1696 }
1697
1698 assert(result);
1699 if (PyList_Sort(result) != 0)
1700 goto error;
1701 else
1702 goto normal_return;
1703
1704 error:
1705 Py_XDECREF(result);
1706 result = NULL;
1707 /* fall through */
1708 normal_return:
1709 Py_XDECREF(masterdict);
1710 return result;
1711}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001712
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001713/*
1714NoObject is usable as a non-NULL undefined value, used by the macro None.
1715There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001716so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001717(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001718*/
1719
Guido van Rossum0c182a11992-03-27 17:26:13 +00001720/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001721static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001722none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001723{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001724 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001725}
1726
Barry Warsaw9bf16442001-01-23 16:24:35 +00001727/* ARGUSED */
1728static void
Tim Peters803526b2002-07-07 05:13:56 +00001729none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001730{
1731 /* This should never get called, but we also don't want to SEGV if
1732 * we accidently decref None out of existance.
1733 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001734 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001735}
1736
1737
Guido van Rossumba21a492001-08-16 08:17:26 +00001738static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001739 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001741 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001742 0,
1743 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001744 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001745 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001746 0, /*tp_getattr*/
1747 0, /*tp_setattr*/
1748 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001749 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001750 0, /*tp_as_number*/
1751 0, /*tp_as_sequence*/
1752 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001753 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001754};
1755
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001756PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001757 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001758};
1759
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001760/* NotImplemented is an object that can be used to signal that an
1761 operation is not implemented for the given type combination. */
1762
1763static PyObject *
1764NotImplemented_repr(PyObject *op)
1765{
1766 return PyString_FromString("NotImplemented");
1767}
1768
1769static PyTypeObject PyNotImplemented_Type = {
1770 PyObject_HEAD_INIT(&PyType_Type)
1771 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001772 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001773 0,
1774 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001775 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001776 0, /*tp_print*/
1777 0, /*tp_getattr*/
1778 0, /*tp_setattr*/
1779 0, /*tp_compare*/
1780 (reprfunc)NotImplemented_repr, /*tp_repr*/
1781 0, /*tp_as_number*/
1782 0, /*tp_as_sequence*/
1783 0, /*tp_as_mapping*/
1784 0, /*tp_hash */
1785};
1786
1787PyObject _Py_NotImplementedStruct = {
1788 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1789};
1790
Guido van Rossumba21a492001-08-16 08:17:26 +00001791void
1792_Py_ReadyTypes(void)
1793{
1794 if (PyType_Ready(&PyType_Type) < 0)
1795 Py_FatalError("Can't initialize 'type'");
1796
Guido van Rossum77f6a652002-04-03 22:41:51 +00001797 if (PyType_Ready(&PyBool_Type) < 0)
1798 Py_FatalError("Can't initialize 'bool'");
1799
Guido van Rossumcacfc072002-05-24 19:01:59 +00001800 if (PyType_Ready(&PyString_Type) < 0)
1801 Py_FatalError("Can't initialize 'str'");
1802
Guido van Rossumba21a492001-08-16 08:17:26 +00001803 if (PyType_Ready(&PyList_Type) < 0)
1804 Py_FatalError("Can't initialize 'list'");
1805
1806 if (PyType_Ready(&PyNone_Type) < 0)
1807 Py_FatalError("Can't initialize type(None)");
1808
1809 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1810 Py_FatalError("Can't initialize type(NotImplemented)");
1811}
1812
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001813
Guido van Rossum84a90321996-05-22 16:34:47 +00001814#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001815
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001816void
Fred Drake100814d2000-07-09 15:48:49 +00001817_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001818{
Tim Peters34592512002-07-11 06:23:50 +00001819 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001820 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001821 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001822 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001823}
1824
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001825void
Fred Drake100814d2000-07-09 15:48:49 +00001826_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001827{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001828#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001829 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001830#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001831 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001832 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001833 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001834 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001835 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001836#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001837 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1838 if (p == op)
1839 break;
1840 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001841 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001842 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001843#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844 op->_ob_next->_ob_prev = op->_ob_prev;
1845 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001846 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001847 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001848}
1849
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001850void
Fred Drake100814d2000-07-09 15:48:49 +00001851_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001852{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001853 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001854 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001855 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001856}
1857
Tim Peters269b2a62003-04-17 19:52:29 +00001858/* Print all live objects. Because PyObject_Print is called, the
1859 * interpreter must be in a healthy state.
1860 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001861void
Fred Drake100814d2000-07-09 15:48:49 +00001862_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001863{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001864 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001865 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001866 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001867 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001868 if (PyObject_Print(op, fp, 0) != 0)
1869 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001870 putc('\n', fp);
1871 }
1872}
1873
Tim Peters269b2a62003-04-17 19:52:29 +00001874/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1875 * doesn't make any calls to the Python C API, so is always safe to call.
1876 */
1877void
1878_Py_PrintReferenceAddresses(FILE *fp)
1879{
1880 PyObject *op;
1881 fprintf(fp, "Remaining object addresses:\n");
1882 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001883 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1884 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001885}
1886
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001887PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001888_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001889{
1890 int i, n;
1891 PyObject *t = NULL;
1892 PyObject *res, *op;
1893
1894 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1895 return NULL;
1896 op = refchain._ob_next;
1897 res = PyList_New(0);
1898 if (res == NULL)
1899 return NULL;
1900 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1901 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001902 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001903 op = op->_ob_next;
1904 if (op == &refchain)
1905 return res;
1906 }
1907 if (PyList_Append(res, op) < 0) {
1908 Py_DECREF(res);
1909 return NULL;
1910 }
1911 op = op->_ob_next;
1912 }
1913 return res;
1914}
1915
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001916#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001917
1918
1919/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001920PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001921
1922
1923/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001924int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001925
1926
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001927/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001928
Thomas Wouters334fb892000-07-25 12:56:38 +00001929void *
Fred Drake100814d2000-07-09 15:48:49 +00001930PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001931{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001932 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001933}
1934
Thomas Wouters334fb892000-07-25 12:56:38 +00001935void *
1936PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001937{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001938 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001939}
1940
1941void
Thomas Wouters334fb892000-07-25 12:56:38 +00001942PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001943{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001944 PyMem_FREE(p);
1945}
1946
1947
Guido van Rossum86610361998-04-10 22:32:46 +00001948/* These methods are used to control infinite recursion in repr, str, print,
1949 etc. Container objects that may recursively contain themselves,
1950 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1951 Py_ReprLeave() to avoid infinite recursion.
1952
1953 Py_ReprEnter() returns 0 the first time it is called for a particular
1954 object and 1 every time thereafter. It returns -1 if an exception
1955 occurred. Py_ReprLeave() has no return value.
1956
1957 See dictobject.c and listobject.c for examples of use.
1958*/
1959
1960#define KEY "Py_Repr"
1961
1962int
Fred Drake100814d2000-07-09 15:48:49 +00001963Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001964{
1965 PyObject *dict;
1966 PyObject *list;
1967 int i;
1968
1969 dict = PyThreadState_GetDict();
1970 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001971 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001972 list = PyDict_GetItemString(dict, KEY);
1973 if (list == NULL) {
1974 list = PyList_New(0);
1975 if (list == NULL)
1976 return -1;
1977 if (PyDict_SetItemString(dict, KEY, list) < 0)
1978 return -1;
1979 Py_DECREF(list);
1980 }
1981 i = PyList_GET_SIZE(list);
1982 while (--i >= 0) {
1983 if (PyList_GET_ITEM(list, i) == obj)
1984 return 1;
1985 }
1986 PyList_Append(list, obj);
1987 return 0;
1988}
1989
1990void
Fred Drake100814d2000-07-09 15:48:49 +00001991Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001992{
1993 PyObject *dict;
1994 PyObject *list;
1995 int i;
1996
1997 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001998 if (dict == NULL)
1999 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002000 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002001 if (list == NULL || !PyList_Check(list))
2002 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002003 i = PyList_GET_SIZE(list);
2004 /* Count backwards because we always expect obj to be list[-1] */
2005 while (--i >= 0) {
2006 if (PyList_GET_ITEM(list, i) == obj) {
2007 PyList_SetSlice(list, i, i + 1, NULL);
2008 break;
2009 }
2010 }
2011}
Guido van Rossumd724b232000-03-13 16:01:29 +00002012
Tim Peters803526b2002-07-07 05:13:56 +00002013/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002014
Tim Peters803526b2002-07-07 05:13:56 +00002015/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002016int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002017
Tim Peters803526b2002-07-07 05:13:56 +00002018/* List of objects that still need to be cleaned up, singly linked via their
2019 * gc headers' gc_prev pointers.
2020 */
2021PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002022
Tim Peters803526b2002-07-07 05:13:56 +00002023/* Add op to the _PyTrash_delete_later list. Called when the current
2024 * call-stack depth gets large. op must be a currently untracked gc'ed
2025 * object, with refcount 0. Py_DECREF must already have been called on it.
2026 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002027void
Fred Drake100814d2000-07-09 15:48:49 +00002028_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002029{
Tim Peters803526b2002-07-07 05:13:56 +00002030 assert(PyObject_IS_GC(op));
2031 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2032 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002033 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002034 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002035}
2036
Tim Peters803526b2002-07-07 05:13:56 +00002037/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2038 * the call-stack unwinds again.
2039 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002040void
Fred Drake100814d2000-07-09 15:48:49 +00002041_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002042{
2043 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002044 PyObject *op = _PyTrash_delete_later;
2045 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002046
Neil Schemenauerf589c052002-03-29 03:05:54 +00002047 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002048 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002049
Tim Peters803526b2002-07-07 05:13:56 +00002050 /* Call the deallocator directly. This used to try to
2051 * fool Py_DECREF into calling it indirectly, but
2052 * Py_DECREF was already called on this object, and in
2053 * assorted non-release builds calling Py_DECREF again ends
2054 * up distorting allocation statistics.
2055 */
2056 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002057 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002058 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002059 --_PyTrash_delete_nesting;
2060 }
2061}