blob: 49b983961a59bacec64872713383c830482ff4d5 [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
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000743/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000744 some types) and decremented on exit. If the count exceeds the
745 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000746
747 This is a tunable parameter that should only affect the performance
748 of comparisons, nothing else. Setting it high makes comparing deeply
749 nested non-cyclical data structures faster, but makes comparing cyclical
750 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000751*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000752#define NESTING_LIMIT 20
753
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000754static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000755
756static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000757get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000758{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000759 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000760 PyObject *tstate_dict, *inprogress;
761
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000762 if (key == NULL) {
763 key = PyString_InternFromString("cmp_state");
764 if (key == NULL)
765 return NULL;
766 }
767
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000768 tstate_dict = PyThreadState_GetDict();
769 if (tstate_dict == NULL) {
770 PyErr_BadInternalCall();
771 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000772 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000773
Tim Peters803526b2002-07-07 05:13:56 +0000774 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000775 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000776 inprogress = PyDict_New();
777 if (inprogress == NULL)
778 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000779 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000780 Py_DECREF(inprogress);
781 return NULL;
782 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000783 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000784 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000785
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000786 return inprogress;
787}
788
Tim Peters4440f222003-01-20 16:54:59 +0000789/* If the comparison "v op w" is already in progress in this thread, returns
790 * a borrowed reference to Py_None (the caller must not decref).
791 * If it's not already in progress, returns "a token" which must eventually
792 * be passed to delete_token(). The caller must not decref this either
793 * (delete_token decrefs it). The token must not survive beyond any point
794 * where v or w may die.
795 * If an error occurs (out-of-memory), returns NULL.
796 */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000797static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000798check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000799{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000800 PyObject *inprogress;
801 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000802 Py_uintptr_t iv = (Py_uintptr_t)v;
803 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000804 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000805
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000806 inprogress = get_inprogress_dict();
807 if (inprogress == NULL)
808 return NULL;
809
810 token = PyTuple_New(3);
811 if (token == NULL)
812 return NULL;
813
814 if (iv <= iw) {
815 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
816 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
817 if (op >= 0)
818 op = swapped_op[op];
819 } else {
820 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
821 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
822 }
823 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
824 if (x == NULL || y == NULL || z == NULL) {
825 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000826 return NULL;
827 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000828
829 if (PyDict_GetItem(inprogress, token) != NULL) {
830 Py_DECREF(token);
831 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000832 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000833
834 if (PyDict_SetItem(inprogress, token, token) < 0) {
835 Py_DECREF(token);
836 return NULL;
837 }
838
839 return token;
840}
841
842static void
843delete_token(PyObject *token)
844{
845 PyObject *inprogress;
846
847 if (token == NULL || token == Py_None)
848 return;
849 inprogress = get_inprogress_dict();
850 if (inprogress == NULL)
851 PyErr_Clear();
852 else
853 PyDict_DelItem(inprogress, token);
854 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000855}
856
Tim Petersc99213f2001-11-04 05:57:16 +0000857/* Compare v to w. Return
858 -1 if v < w or exception (PyErr_Occurred() true in latter case).
859 0 if v == w.
860 1 if v > w.
861 XXX The docs (C API manual) say the return value is undefined in case
862 XXX of error.
863*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000864int
Fred Drake100814d2000-07-09 15:48:49 +0000865PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000866{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000867 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000868 int result;
869
Jack Jansend49cbe12000-08-22 21:52:51 +0000870#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000871 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000872 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000873 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000874 }
875#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000876 if (v == NULL || w == NULL) {
877 PyErr_BadInternalCall();
878 return -1;
879 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880 if (v == w)
881 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000882 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000883 compare_nesting++;
884 if (compare_nesting > NESTING_LIMIT &&
Tim Peters4440f222003-01-20 16:54:59 +0000885 (vtp->tp_as_mapping || vtp->tp_as_sequence) &&
886 !PyString_CheckExact(v) &&
887 !PyTuple_CheckExact(v)) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000888 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000889 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000890
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000891 if (token == NULL) {
892 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000893 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000894 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000895 /* already comparing these objects. assume
896 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000897 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000898 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000899 else {
900 result = do_cmp(v, w);
901 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000902 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000903 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000904 else {
905 result = do_cmp(v, w);
906 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000907 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000908 return result < 0 ? -1 : result;
909}
910
Tim Petersc99213f2001-11-04 05:57:16 +0000911/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000912static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000913convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000914{
Guido van Rossume797ec12001-01-17 15:24:28 +0000915 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000916 switch (op) {
917 case Py_LT: c = c < 0; break;
918 case Py_LE: c = c <= 0; break;
919 case Py_EQ: c = c == 0; break;
920 case Py_NE: c = c != 0; break;
921 case Py_GT: c = c > 0; break;
922 case Py_GE: c = c >= 0; break;
923 }
924 result = c ? Py_True : Py_False;
925 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000926 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000927}
Tim Peters803526b2002-07-07 05:13:56 +0000928
Tim Petersc99213f2001-11-04 05:57:16 +0000929/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
930 Return
931 NULL if error
932 Py_True if v op w
933 Py_False if not (v op w)
934*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000935static PyObject *
936try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
937{
938 int c;
939
940 c = try_3way_compare(v, w);
941 if (c >= 2)
942 c = default_3way_compare(v, w);
943 if (c <= -2)
944 return NULL;
945 return convert_3way_to_object(op, c);
946}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000947
Tim Petersc99213f2001-11-04 05:57:16 +0000948/* Do rich comparison on v and w. Return
949 NULL if error
950 Else a new reference to an object other than Py_NotImplemented, usually(?):
951 Py_True if v op w
952 Py_False if not (v op w)
953*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000954static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000955do_richcmp(PyObject *v, PyObject *w, int op)
956{
957 PyObject *res;
958
959 res = try_rich_compare(v, w, op);
960 if (res != Py_NotImplemented)
961 return res;
962 Py_DECREF(res);
963
964 return try_3way_to_rich_compare(v, w, op);
965}
966
Tim Petersc99213f2001-11-04 05:57:16 +0000967/* Return:
968 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000969 some object not equal to NotImplemented if it is implemented
970 (this latter object may not be a Boolean).
971*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000972PyObject *
973PyObject_RichCompare(PyObject *v, PyObject *w, int op)
974{
975 PyObject *res;
976
977 assert(Py_LT <= op && op <= Py_GE);
978
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000979 compare_nesting++;
980 if (compare_nesting > NESTING_LIMIT &&
Tim Peters4440f222003-01-20 16:54:59 +0000981 (v->ob_type->tp_as_mapping || v->ob_type->tp_as_sequence) &&
982 !PyString_CheckExact(v) &&
983 !PyTuple_CheckExact(v)) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000984 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000985 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000986 if (token == NULL) {
987 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000988 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000989 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000990 else if (token == Py_None) {
991 /* already comparing these objects with this operator.
992 assume they're equal until shown otherwise */
993 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000994 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000995 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000996 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000997 else {
998 PyErr_SetString(PyExc_ValueError,
999 "can't order recursive values");
1000 res = NULL;
1001 }
1002 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001003 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +00001004 else {
1005 res = do_richcmp(v, w, op);
1006 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001007 }
Tim Peters67754e92001-11-04 07:29:31 +00001008 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +00001009 }
Tim Peters67754e92001-11-04 07:29:31 +00001010
1011 /* No nesting extremism.
1012 If the types are equal, and not old-style instances, try to
1013 get out cheap (don't bother with coercions etc.). */
1014 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1015 cmpfunc fcmp;
1016 richcmpfunc frich = RICHCOMPARE(v->ob_type);
1017 /* If the type has richcmp, try it first. try_rich_compare
1018 tries it two-sided, which is not needed since we've a
1019 single type only. */
1020 if (frich != NULL) {
1021 res = (*frich)(v, w, op);
1022 if (res != Py_NotImplemented)
1023 goto Done;
1024 Py_DECREF(res);
1025 }
1026 /* No richcmp, or this particular richmp not implemented.
1027 Try 3-way cmp. */
1028 fcmp = v->ob_type->tp_compare;
1029 if (fcmp != NULL) {
1030 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +00001031 c = adjust_tp_compare(c);
1032 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +00001033 res = NULL;
1034 goto Done;
1035 }
1036 res = convert_3way_to_object(op, c);
1037 goto Done;
1038 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001039 }
Tim Peters67754e92001-11-04 07:29:31 +00001040
1041 /* Fast path not taken, or couldn't deliver a useful result. */
1042 res = do_richcmp(v, w, op);
1043Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001044 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +00001045 return res;
1046}
1047
Tim Petersde9725f2001-05-05 10:06:17 +00001048/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +00001049int
1050PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
1051{
1052 PyObject *res = PyObject_RichCompare(v, w, op);
1053 int ok;
1054
1055 if (res == NULL)
1056 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +00001057 if (PyBool_Check(res))
1058 ok = (res == Py_True);
1059 else
1060 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +00001061 Py_DECREF(res);
1062 return ok;
1063}
Fred Drake13634cf2000-06-29 19:17:04 +00001064
1065/* Set of hash utility functions to help maintaining the invariant that
1066 iff a==b then hash(a)==hash(b)
1067
1068 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1069*/
1070
1071long
Fred Drake100814d2000-07-09 15:48:49 +00001072_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001073{
Tim Peters39dce292000-08-15 03:34:48 +00001074 double intpart, fractpart;
1075 int expo;
1076 long hipart;
1077 long x; /* the final hash value */
1078 /* This is designed so that Python numbers of different types
1079 * that compare equal hash to the same value; otherwise comparisons
1080 * of mapping keys will turn out weird.
1081 */
1082
1083#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1084{
1085 extended e;
1086 fractpart = modf(v, &e);
1087 intpart = e;
1088}
1089#else
1090 fractpart = modf(v, &intpart);
1091#endif
1092 if (fractpart == 0.0) {
1093 /* This must return the same hash as an equal int or long. */
1094 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1095 /* Convert to long and use its hash. */
1096 PyObject *plong; /* converted to Python long */
1097 if (Py_IS_INFINITY(intpart))
1098 /* can't convert to long int -- arbitrary */
1099 v = v < 0 ? -271828.0 : 314159.0;
1100 plong = PyLong_FromDouble(v);
1101 if (plong == NULL)
1102 return -1;
1103 x = PyObject_Hash(plong);
1104 Py_DECREF(plong);
1105 return x;
1106 }
1107 /* Fits in a C long == a Python int, so is its own hash. */
1108 x = (long)intpart;
1109 if (x == -1)
1110 x = -2;
1111 return x;
1112 }
1113 /* The fractional part is non-zero, so we don't have to worry about
1114 * making this match the hash of some other type.
1115 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001116 * Since the VAX D double format has 56 mantissa bits, which is the
1117 * most of any double format in use, each of these parts may have as
1118 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001119 * So, assuming sizeof(long) >= 4, each part can be broken into two
1120 * longs; frexp and multiplication are used to do that.
1121 * Also, since the Cray double format has 15 exponent bits, which is
1122 * the most of any double format in use, shifting the exponent field
1123 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001124 */
Tim Peters39dce292000-08-15 03:34:48 +00001125 v = frexp(v, &expo);
1126 v *= 2147483648.0; /* 2**31 */
1127 hipart = (long)v; /* take the top 32 bits */
1128 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1129 x = hipart + (long)v + (expo << 15);
1130 if (x == -1)
1131 x = -2;
1132 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001133}
1134
1135long
Fred Drake100814d2000-07-09 15:48:49 +00001136_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001137{
1138#if SIZEOF_LONG >= SIZEOF_VOID_P
1139 return (long)p;
1140#else
1141 /* convert to a Python long and hash that */
1142 PyObject* longobj;
1143 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001144
Fred Drake13634cf2000-06-29 19:17:04 +00001145 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1146 x = -1;
1147 goto finally;
1148 }
1149 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001150
Fred Drake13634cf2000-06-29 19:17:04 +00001151finally:
1152 Py_XDECREF(longobj);
1153 return x;
1154#endif
1155}
1156
1157
Guido van Rossum9bfef441993-03-29 10:43:31 +00001158long
Fred Drake100814d2000-07-09 15:48:49 +00001159PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001160{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001161 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001162 if (tp->tp_hash != NULL)
1163 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001164 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001165 return _Py_HashPointer(v); /* Use address as hash value */
1166 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001167 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001168 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001169 return -1;
1170}
1171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001172PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001173PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001174{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001176
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001178 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179 w = PyString_InternFromString(name);
1180 if (w == NULL)
1181 return NULL;
1182 res = PyObject_GetAttr(v, w);
1183 Py_XDECREF(w);
1184 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001185}
1186
1187int
Fred Drake100814d2000-07-09 15:48:49 +00001188PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001189{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001190 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001191 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001192 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001193 return 1;
1194 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001195 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001196 return 0;
1197}
1198
1199int
Fred Drake100814d2000-07-09 15:48:49 +00001200PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001201{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 PyObject *s;
1203 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001204
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001206 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 s = PyString_InternFromString(name);
1208 if (s == NULL)
1209 return -1;
1210 res = PyObject_SetAttr(v, s, w);
1211 Py_XDECREF(s);
1212 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001213}
1214
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001215PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001216PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001217{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 PyTypeObject *tp = v->ob_type;
1219
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001220 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001221#ifdef Py_USING_UNICODE
1222 /* The Unicode to string conversion is done here because the
1223 existing tp_getattro slots expect a string object as name
1224 and we wouldn't want to break those. */
1225 if (PyUnicode_Check(name)) {
1226 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1227 if (name == NULL)
1228 return NULL;
1229 }
1230 else
1231#endif
1232 {
1233 PyErr_SetString(PyExc_TypeError,
1234 "attribute name must be string");
1235 return NULL;
1236 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001237 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 if (tp->tp_getattro != NULL)
1239 return (*tp->tp_getattro)(v, name);
1240 if (tp->tp_getattr != NULL)
1241 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1242 PyErr_Format(PyExc_AttributeError,
1243 "'%.50s' object has no attribute '%.400s'",
1244 tp->tp_name, PyString_AS_STRING(name));
1245 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001246}
1247
1248int
Fred Drake100814d2000-07-09 15:48:49 +00001249PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001250{
1251 PyObject *res = PyObject_GetAttr(v, name);
1252 if (res != NULL) {
1253 Py_DECREF(res);
1254 return 1;
1255 }
1256 PyErr_Clear();
1257 return 0;
1258}
1259
1260int
Fred Drake100814d2000-07-09 15:48:49 +00001261PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001262{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001264 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001265
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001266 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001267#ifdef Py_USING_UNICODE
1268 /* The Unicode to string conversion is done here because the
1269 existing tp_setattro slots expect a string object as name
1270 and we wouldn't want to break those. */
1271 if (PyUnicode_Check(name)) {
1272 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1273 if (name == NULL)
1274 return -1;
1275 }
Tim Peters803526b2002-07-07 05:13:56 +00001276 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001277#endif
1278 {
1279 PyErr_SetString(PyExc_TypeError,
1280 "attribute name must be string");
1281 return -1;
1282 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001283 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001284 else
1285 Py_INCREF(name);
1286
1287 PyString_InternInPlace(&name);
1288 if (tp->tp_setattro != NULL) {
1289 err = (*tp->tp_setattro)(v, name, value);
1290 Py_DECREF(name);
1291 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001292 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293 if (tp->tp_setattr != NULL) {
1294 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1295 Py_DECREF(name);
1296 return err;
1297 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001298 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1300 PyErr_Format(PyExc_TypeError,
1301 "'%.100s' object has no attributes "
1302 "(%s .%.100s)",
1303 tp->tp_name,
1304 value==NULL ? "del" : "assign to",
1305 PyString_AS_STRING(name));
1306 else
1307 PyErr_Format(PyExc_TypeError,
1308 "'%.100s' object has only read-only attributes "
1309 "(%s .%.100s)",
1310 tp->tp_name,
1311 value==NULL ? "del" : "assign to",
1312 PyString_AS_STRING(name));
1313 return -1;
1314}
1315
1316/* Helper to get a pointer to an object's __dict__ slot, if any */
1317
1318PyObject **
1319_PyObject_GetDictPtr(PyObject *obj)
1320{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 long dictoffset;
1322 PyTypeObject *tp = obj->ob_type;
1323
1324 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1325 return NULL;
1326 dictoffset = tp->tp_dictoffset;
1327 if (dictoffset == 0)
1328 return NULL;
1329 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001330 int tsize;
1331 size_t size;
1332
1333 tsize = ((PyVarObject *)obj)->ob_size;
1334 if (tsize < 0)
1335 tsize = -tsize;
1336 size = _PyObject_VAR_SIZE(tp, tsize);
1337
Tim Peters6d483d32001-10-06 21:27:34 +00001338 dictoffset += (long)size;
1339 assert(dictoffset > 0);
1340 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341 }
1342 return (PyObject **) ((char *)obj + dictoffset);
1343}
1344
1345/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1346
1347PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001348PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001349{
1350 Py_INCREF(obj);
1351 return obj;
1352}
1353
1354PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001355PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1356{
1357 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001358 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001361 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362 PyObject **dictptr;
1363
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001364 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001365#ifdef Py_USING_UNICODE
1366 /* The Unicode to string conversion is done here because the
1367 existing tp_setattro slots expect a string object as name
1368 and we wouldn't want to break those. */
1369 if (PyUnicode_Check(name)) {
1370 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1371 if (name == NULL)
1372 return NULL;
1373 }
Tim Peters803526b2002-07-07 05:13:56 +00001374 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001375#endif
1376 {
1377 PyErr_SetString(PyExc_TypeError,
1378 "attribute name must be string");
1379 return NULL;
1380 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001381 }
1382 else
1383 Py_INCREF(name);
1384
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001386 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001387 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 }
1389
Guido van Rossum056fbf42002-08-19 19:22:50 +00001390 /* Inline _PyType_Lookup */
1391 {
1392 int i, n;
1393 PyObject *mro, *base, *dict;
1394
1395 /* Look in tp_dict of types in MRO */
1396 mro = tp->tp_mro;
1397 assert(mro != NULL);
1398 assert(PyTuple_Check(mro));
1399 n = PyTuple_GET_SIZE(mro);
1400 for (i = 0; i < n; i++) {
1401 base = PyTuple_GET_ITEM(mro, i);
1402 if (PyClass_Check(base))
1403 dict = ((PyClassObject *)base)->cl_dict;
1404 else {
1405 assert(PyType_Check(base));
1406 dict = ((PyTypeObject *)base)->tp_dict;
1407 }
1408 assert(dict && PyDict_Check(dict));
1409 descr = PyDict_GetItem(dict, name);
1410 if (descr != NULL)
1411 break;
1412 }
1413 }
1414
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001416 if (descr != NULL &&
1417 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001419 if (f != NULL && PyDescr_IsData(descr)) {
1420 res = f(descr, obj, (PyObject *)obj->ob_type);
1421 goto done;
1422 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423 }
1424
Guido van Rossumc66ff442002-08-19 16:50:48 +00001425 /* Inline _PyObject_GetDictPtr */
1426 dictoffset = tp->tp_dictoffset;
1427 if (dictoffset != 0) {
1428 PyObject *dict;
1429 if (dictoffset < 0) {
1430 int tsize;
1431 size_t size;
1432
1433 tsize = ((PyVarObject *)obj)->ob_size;
1434 if (tsize < 0)
1435 tsize = -tsize;
1436 size = _PyObject_VAR_SIZE(tp, tsize);
1437
1438 dictoffset += (long)size;
1439 assert(dictoffset > 0);
1440 assert(dictoffset % SIZEOF_VOID_P == 0);
1441 }
1442 dictptr = (PyObject **) ((char *)obj + dictoffset);
1443 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001445 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001446 if (res != NULL) {
1447 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001448 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001449 }
1450 }
1451 }
1452
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001453 if (f != NULL) {
1454 res = f(descr, obj, (PyObject *)obj->ob_type);
1455 goto done;
1456 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001457
1458 if (descr != NULL) {
1459 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001460 res = descr;
1461 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001462 }
1463
1464 PyErr_Format(PyExc_AttributeError,
1465 "'%.50s' object has no attribute '%.400s'",
1466 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001467 done:
1468 Py_DECREF(name);
1469 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470}
1471
1472int
1473PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1474{
1475 PyTypeObject *tp = obj->ob_type;
1476 PyObject *descr;
1477 descrsetfunc f;
1478 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001479 int res = -1;
1480
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001481 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001482#ifdef Py_USING_UNICODE
1483 /* The Unicode to string conversion is done here because the
1484 existing tp_setattro slots expect a string object as name
1485 and we wouldn't want to break those. */
1486 if (PyUnicode_Check(name)) {
1487 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1488 if (name == NULL)
1489 return -1;
1490 }
Tim Peters803526b2002-07-07 05:13:56 +00001491 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001492#endif
1493 {
1494 PyErr_SetString(PyExc_TypeError,
1495 "attribute name must be string");
1496 return -1;
1497 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001498 }
1499 else
1500 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001501
1502 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001503 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001504 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001505 }
1506
1507 descr = _PyType_Lookup(tp, name);
1508 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001509 if (descr != NULL &&
1510 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001511 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001512 if (f != NULL && PyDescr_IsData(descr)) {
1513 res = f(descr, obj, value);
1514 goto done;
1515 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516 }
1517
1518 dictptr = _PyObject_GetDictPtr(obj);
1519 if (dictptr != NULL) {
1520 PyObject *dict = *dictptr;
1521 if (dict == NULL && value != NULL) {
1522 dict = PyDict_New();
1523 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001524 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525 *dictptr = dict;
1526 }
1527 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001528 if (value == NULL)
1529 res = PyDict_DelItem(dict, name);
1530 else
1531 res = PyDict_SetItem(dict, name, value);
1532 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1533 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001534 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001535 }
1536 }
1537
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001538 if (f != NULL) {
1539 res = f(descr, obj, value);
1540 goto done;
1541 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001542
1543 if (descr == NULL) {
1544 PyErr_Format(PyExc_AttributeError,
1545 "'%.50s' object has no attribute '%.400s'",
1546 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001547 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001548 }
1549
1550 PyErr_Format(PyExc_AttributeError,
1551 "'%.50s' object attribute '%.400s' is read-only",
1552 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001553 done:
1554 Py_DECREF(name);
1555 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001556}
1557
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001558/* Test a value used as condition, e.g., in a for or if statement.
1559 Return -1 if an error occurred */
1560
1561int
Fred Drake100814d2000-07-09 15:48:49 +00001562PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001563{
1564 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001565 if (v == Py_True)
1566 return 1;
1567 if (v == Py_False)
1568 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001569 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001570 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001571 else if (v->ob_type->tp_as_number != NULL &&
1572 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001573 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001574 else if (v->ob_type->tp_as_mapping != NULL &&
1575 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001576 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001577 else if (v->ob_type->tp_as_sequence != NULL &&
1578 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001579 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1580 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001581 return 1;
1582 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001583}
1584
Tim Peters803526b2002-07-07 05:13:56 +00001585/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001586 Return -1 if an error occurred */
1587
1588int
Fred Drake100814d2000-07-09 15:48:49 +00001589PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001590{
1591 int res;
1592 res = PyObject_IsTrue(v);
1593 if (res < 0)
1594 return res;
1595 return res == 0;
1596}
1597
Guido van Rossum5524a591995-01-10 15:26:20 +00001598/* Coerce two numeric types to the "larger" one.
1599 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001600 Return value:
1601 -1 if an error occurred;
1602 0 if the coercion succeeded (and then the reference counts are increased);
1603 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001604*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001605int
Fred Drake100814d2000-07-09 15:48:49 +00001606PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001607{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001608 register PyObject *v = *pv;
1609 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001610 int res;
1611
Guido van Rossum517c7d42002-04-26 02:49:14 +00001612 /* Shortcut only for old-style types */
1613 if (v->ob_type == w->ob_type &&
1614 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1615 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001616 Py_INCREF(v);
1617 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001618 return 0;
1619 }
1620 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1621 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1622 if (res <= 0)
1623 return res;
1624 }
1625 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1626 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1627 if (res <= 0)
1628 return res;
1629 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001630 return 1;
1631}
1632
Guido van Rossume797ec12001-01-17 15:24:28 +00001633/* Coerce two numeric types to the "larger" one.
1634 Increment the reference count on each argument.
1635 Return -1 and raise an exception if no coercion is possible
1636 (and then no reference count is incremented).
1637*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001638int
Fred Drake100814d2000-07-09 15:48:49 +00001639PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001640{
1641 int err = PyNumber_CoerceEx(pv, pw);
1642 if (err <= 0)
1643 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001644 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001645 return -1;
1646}
1647
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001648
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001649/* Test whether an object can be called */
1650
1651int
Fred Drake100814d2000-07-09 15:48:49 +00001652PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001653{
1654 if (x == NULL)
1655 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001656 if (PyInstance_Check(x)) {
1657 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001658 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001659 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001660 return 0;
1661 }
1662 /* Could test recursively but don't, for fear of endless
1663 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001664 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001665 return 1;
1666 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001667 else {
1668 return x->ob_type->tp_call != NULL;
1669 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001670}
1671
Tim Peters7eea37e2001-09-04 22:08:56 +00001672/* Helper for PyObject_Dir.
1673 Merge the __dict__ of aclass into dict, and recursively also all
1674 the __dict__s of aclass's base classes. The order of merging isn't
1675 defined, as it's expected that only the final set of dict keys is
1676 interesting.
1677 Return 0 on success, -1 on error.
1678*/
1679
1680static int
1681merge_class_dict(PyObject* dict, PyObject* aclass)
1682{
1683 PyObject *classdict;
1684 PyObject *bases;
1685
1686 assert(PyDict_Check(dict));
1687 assert(aclass);
1688
1689 /* Merge in the type's dict (if any). */
1690 classdict = PyObject_GetAttrString(aclass, "__dict__");
1691 if (classdict == NULL)
1692 PyErr_Clear();
1693 else {
1694 int status = PyDict_Update(dict, classdict);
1695 Py_DECREF(classdict);
1696 if (status < 0)
1697 return -1;
1698 }
1699
1700 /* Recursively merge in the base types' (if any) dicts. */
1701 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001702 if (bases == NULL)
1703 PyErr_Clear();
1704 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001705 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001706 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001707 n = PySequence_Size(bases); /* This better be right */
1708 if (n < 0)
1709 PyErr_Clear();
1710 else {
1711 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001712 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001713 PyObject *base = PySequence_GetItem(bases, i);
1714 if (base == NULL) {
1715 Py_DECREF(bases);
1716 return -1;
1717 }
Tim Peters18e70832003-02-05 19:35:19 +00001718 status = merge_class_dict(dict, base);
1719 Py_DECREF(base);
1720 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001721 Py_DECREF(bases);
1722 return -1;
1723 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001724 }
1725 }
1726 Py_DECREF(bases);
1727 }
1728 return 0;
1729}
1730
Tim Peters305b5852001-09-17 02:38:46 +00001731/* Helper for PyObject_Dir.
1732 If obj has an attr named attrname that's a list, merge its string
1733 elements into keys of dict.
1734 Return 0 on success, -1 on error. Errors due to not finding the attr,
1735 or the attr not being a list, are suppressed.
1736*/
1737
1738static int
1739merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1740{
1741 PyObject *list;
1742 int result = 0;
1743
1744 assert(PyDict_Check(dict));
1745 assert(obj);
1746 assert(attrname);
1747
1748 list = PyObject_GetAttrString(obj, attrname);
1749 if (list == NULL)
1750 PyErr_Clear();
1751
1752 else if (PyList_Check(list)) {
1753 int i;
1754 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1755 PyObject *item = PyList_GET_ITEM(list, i);
1756 if (PyString_Check(item)) {
1757 result = PyDict_SetItem(dict, item, Py_None);
1758 if (result < 0)
1759 break;
1760 }
1761 }
1762 }
1763
1764 Py_XDECREF(list);
1765 return result;
1766}
1767
Tim Peters7eea37e2001-09-04 22:08:56 +00001768/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1769 docstring, which should be kept in synch with this implementation. */
1770
1771PyObject *
1772PyObject_Dir(PyObject *arg)
1773{
1774 /* Set exactly one of these non-NULL before the end. */
1775 PyObject *result = NULL; /* result list */
1776 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1777
1778 /* If NULL arg, return the locals. */
1779 if (arg == NULL) {
1780 PyObject *locals = PyEval_GetLocals();
1781 if (locals == NULL)
1782 goto error;
1783 result = PyDict_Keys(locals);
1784 if (result == NULL)
1785 goto error;
1786 }
1787
1788 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001789 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001790 masterdict = PyObject_GetAttrString(arg, "__dict__");
1791 if (masterdict == NULL)
1792 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001793 if (!PyDict_Check(masterdict)) {
1794 PyErr_SetString(PyExc_TypeError,
1795 "module.__dict__ is not a dictionary");
1796 goto error;
1797 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001798 }
1799
1800 /* Elif some form of type or class, grab its dict and its bases.
1801 We deliberately don't suck up its __class__, as methods belonging
1802 to the metaclass would probably be more confusing than helpful. */
1803 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1804 masterdict = PyDict_New();
1805 if (masterdict == NULL)
1806 goto error;
1807 if (merge_class_dict(masterdict, arg) < 0)
1808 goto error;
1809 }
1810
1811 /* Else look at its dict, and the attrs reachable from its class. */
1812 else {
1813 PyObject *itsclass;
1814 /* Create a dict to start with. CAUTION: Not everything
1815 responding to __dict__ returns a dict! */
1816 masterdict = PyObject_GetAttrString(arg, "__dict__");
1817 if (masterdict == NULL) {
1818 PyErr_Clear();
1819 masterdict = PyDict_New();
1820 }
1821 else if (!PyDict_Check(masterdict)) {
1822 Py_DECREF(masterdict);
1823 masterdict = PyDict_New();
1824 }
1825 else {
1826 /* The object may have returned a reference to its
1827 dict, so copy it to avoid mutating it. */
1828 PyObject *temp = PyDict_Copy(masterdict);
1829 Py_DECREF(masterdict);
1830 masterdict = temp;
1831 }
1832 if (masterdict == NULL)
1833 goto error;
1834
Tim Peters305b5852001-09-17 02:38:46 +00001835 /* Merge in __members__ and __methods__ (if any).
1836 XXX Would like this to go away someday; for now, it's
1837 XXX needed to get at im_self etc of method objects. */
1838 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1839 goto error;
1840 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1841 goto error;
1842
Tim Peters7eea37e2001-09-04 22:08:56 +00001843 /* Merge in attrs reachable from its class.
1844 CAUTION: Not all objects have a __class__ attr. */
1845 itsclass = PyObject_GetAttrString(arg, "__class__");
1846 if (itsclass == NULL)
1847 PyErr_Clear();
1848 else {
1849 int status = merge_class_dict(masterdict, itsclass);
1850 Py_DECREF(itsclass);
1851 if (status < 0)
1852 goto error;
1853 }
1854 }
1855
1856 assert((result == NULL) ^ (masterdict == NULL));
1857 if (masterdict != NULL) {
1858 /* The result comes from its keys. */
1859 assert(result == NULL);
1860 result = PyDict_Keys(masterdict);
1861 if (result == NULL)
1862 goto error;
1863 }
1864
1865 assert(result);
1866 if (PyList_Sort(result) != 0)
1867 goto error;
1868 else
1869 goto normal_return;
1870
1871 error:
1872 Py_XDECREF(result);
1873 result = NULL;
1874 /* fall through */
1875 normal_return:
1876 Py_XDECREF(masterdict);
1877 return result;
1878}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001879
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880/*
1881NoObject is usable as a non-NULL undefined value, used by the macro None.
1882There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001883so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001884(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001885*/
1886
Guido van Rossum0c182a11992-03-27 17:26:13 +00001887/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001888static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001889none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001890{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001891 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892}
1893
Barry Warsaw9bf16442001-01-23 16:24:35 +00001894/* ARGUSED */
1895static void
Tim Peters803526b2002-07-07 05:13:56 +00001896none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001897{
1898 /* This should never get called, but we also don't want to SEGV if
1899 * we accidently decref None out of existance.
1900 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001901 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001902}
1903
1904
Guido van Rossumba21a492001-08-16 08:17:26 +00001905static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001906 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001907 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001908 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001909 0,
1910 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001911 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001912 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001913 0, /*tp_getattr*/
1914 0, /*tp_setattr*/
1915 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001916 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001917 0, /*tp_as_number*/
1918 0, /*tp_as_sequence*/
1919 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001920 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001921};
1922
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001923PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001924 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001925};
1926
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001927/* NotImplemented is an object that can be used to signal that an
1928 operation is not implemented for the given type combination. */
1929
1930static PyObject *
1931NotImplemented_repr(PyObject *op)
1932{
1933 return PyString_FromString("NotImplemented");
1934}
1935
1936static PyTypeObject PyNotImplemented_Type = {
1937 PyObject_HEAD_INIT(&PyType_Type)
1938 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001939 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001940 0,
1941 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001942 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001943 0, /*tp_print*/
1944 0, /*tp_getattr*/
1945 0, /*tp_setattr*/
1946 0, /*tp_compare*/
1947 (reprfunc)NotImplemented_repr, /*tp_repr*/
1948 0, /*tp_as_number*/
1949 0, /*tp_as_sequence*/
1950 0, /*tp_as_mapping*/
1951 0, /*tp_hash */
1952};
1953
1954PyObject _Py_NotImplementedStruct = {
1955 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1956};
1957
Guido van Rossumba21a492001-08-16 08:17:26 +00001958void
1959_Py_ReadyTypes(void)
1960{
1961 if (PyType_Ready(&PyType_Type) < 0)
1962 Py_FatalError("Can't initialize 'type'");
1963
Guido van Rossum77f6a652002-04-03 22:41:51 +00001964 if (PyType_Ready(&PyBool_Type) < 0)
1965 Py_FatalError("Can't initialize 'bool'");
1966
Guido van Rossumcacfc072002-05-24 19:01:59 +00001967 if (PyType_Ready(&PyString_Type) < 0)
1968 Py_FatalError("Can't initialize 'str'");
1969
Guido van Rossumba21a492001-08-16 08:17:26 +00001970 if (PyType_Ready(&PyList_Type) < 0)
1971 Py_FatalError("Can't initialize 'list'");
1972
1973 if (PyType_Ready(&PyNone_Type) < 0)
1974 Py_FatalError("Can't initialize type(None)");
1975
1976 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1977 Py_FatalError("Can't initialize type(NotImplemented)");
1978}
1979
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001980
Guido van Rossum84a90321996-05-22 16:34:47 +00001981#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001982
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001983void
Fred Drake100814d2000-07-09 15:48:49 +00001984_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001985{
Tim Peters34592512002-07-11 06:23:50 +00001986 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001987 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001988 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001989 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001990}
1991
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001992void
Fred Drake100814d2000-07-09 15:48:49 +00001993_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001994{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001995#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001996 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001997#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001998 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001999 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002000 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00002001 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002002 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002003#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00002004 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
2005 if (p == op)
2006 break;
2007 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00002008 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002009 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002010#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002011 op->_ob_next->_ob_prev = op->_ob_prev;
2012 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002013 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00002014 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002015}
2016
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002017void
Fred Drake100814d2000-07-09 15:48:49 +00002018_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002019{
Guido van Rossum9776adf1994-09-07 14:36:45 +00002020 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002021 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00002022 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002023}
2024
Tim Peters269b2a62003-04-17 19:52:29 +00002025/* Print all live objects. Because PyObject_Print is called, the
2026 * interpreter must be in a healthy state.
2027 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002028void
Fred Drake100814d2000-07-09 15:48:49 +00002029_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002030{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002031 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00002032 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002033 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00002034 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002035 if (PyObject_Print(op, fp, 0) != 0)
2036 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002037 putc('\n', fp);
2038 }
2039}
2040
Tim Peters269b2a62003-04-17 19:52:29 +00002041/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
2042 * doesn't make any calls to the Python C API, so is always safe to call.
2043 */
2044void
2045_Py_PrintReferenceAddresses(FILE *fp)
2046{
2047 PyObject *op;
2048 fprintf(fp, "Remaining object addresses:\n");
2049 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
2050 fprintf(fp, "%p [%d]\n", op, op->ob_refcnt);
2051}
2052
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002053PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002054_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002055{
2056 int i, n;
2057 PyObject *t = NULL;
2058 PyObject *res, *op;
2059
2060 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2061 return NULL;
2062 op = refchain._ob_next;
2063 res = PyList_New(0);
2064 if (res == NULL)
2065 return NULL;
2066 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2067 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00002068 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002069 op = op->_ob_next;
2070 if (op == &refchain)
2071 return res;
2072 }
2073 if (PyList_Append(res, op) < 0) {
2074 Py_DECREF(res);
2075 return NULL;
2076 }
2077 op = op->_ob_next;
2078 }
2079 return res;
2080}
2081
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002082#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002083
2084
2085/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00002086PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00002087
2088
2089/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00002090int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002091
2092
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00002093/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00002094
Thomas Wouters334fb892000-07-25 12:56:38 +00002095void *
Fred Drake100814d2000-07-09 15:48:49 +00002096PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002097{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002098 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002099}
2100
Thomas Wouters334fb892000-07-25 12:56:38 +00002101void *
2102PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002103{
Tim Petersaf3e8de2002-04-12 07:22:56 +00002104 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002105}
2106
2107void
Thomas Wouters334fb892000-07-25 12:56:38 +00002108PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002109{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002110 PyMem_FREE(p);
2111}
2112
2113
Guido van Rossum86610361998-04-10 22:32:46 +00002114/* These methods are used to control infinite recursion in repr, str, print,
2115 etc. Container objects that may recursively contain themselves,
2116 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2117 Py_ReprLeave() to avoid infinite recursion.
2118
2119 Py_ReprEnter() returns 0 the first time it is called for a particular
2120 object and 1 every time thereafter. It returns -1 if an exception
2121 occurred. Py_ReprLeave() has no return value.
2122
2123 See dictobject.c and listobject.c for examples of use.
2124*/
2125
2126#define KEY "Py_Repr"
2127
2128int
Fred Drake100814d2000-07-09 15:48:49 +00002129Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002130{
2131 PyObject *dict;
2132 PyObject *list;
2133 int i;
2134
2135 dict = PyThreadState_GetDict();
2136 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00002137 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002138 list = PyDict_GetItemString(dict, KEY);
2139 if (list == NULL) {
2140 list = PyList_New(0);
2141 if (list == NULL)
2142 return -1;
2143 if (PyDict_SetItemString(dict, KEY, list) < 0)
2144 return -1;
2145 Py_DECREF(list);
2146 }
2147 i = PyList_GET_SIZE(list);
2148 while (--i >= 0) {
2149 if (PyList_GET_ITEM(list, i) == obj)
2150 return 1;
2151 }
2152 PyList_Append(list, obj);
2153 return 0;
2154}
2155
2156void
Fred Drake100814d2000-07-09 15:48:49 +00002157Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002158{
2159 PyObject *dict;
2160 PyObject *list;
2161 int i;
2162
2163 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002164 if (dict == NULL)
2165 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002166 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002167 if (list == NULL || !PyList_Check(list))
2168 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002169 i = PyList_GET_SIZE(list);
2170 /* Count backwards because we always expect obj to be list[-1] */
2171 while (--i >= 0) {
2172 if (PyList_GET_ITEM(list, i) == obj) {
2173 PyList_SetSlice(list, i, i + 1, NULL);
2174 break;
2175 }
2176 }
2177}
Guido van Rossumd724b232000-03-13 16:01:29 +00002178
Tim Peters803526b2002-07-07 05:13:56 +00002179/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002180
Tim Peters803526b2002-07-07 05:13:56 +00002181/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002182int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002183
Tim Peters803526b2002-07-07 05:13:56 +00002184/* List of objects that still need to be cleaned up, singly linked via their
2185 * gc headers' gc_prev pointers.
2186 */
2187PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002188
Tim Peters803526b2002-07-07 05:13:56 +00002189/* Add op to the _PyTrash_delete_later list. Called when the current
2190 * call-stack depth gets large. op must be a currently untracked gc'ed
2191 * object, with refcount 0. Py_DECREF must already have been called on it.
2192 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002193void
Fred Drake100814d2000-07-09 15:48:49 +00002194_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002195{
Tim Peters803526b2002-07-07 05:13:56 +00002196 assert(PyObject_IS_GC(op));
2197 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2198 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002199 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002200 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002201}
2202
Tim Peters803526b2002-07-07 05:13:56 +00002203/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2204 * the call-stack unwinds again.
2205 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002206void
Fred Drake100814d2000-07-09 15:48:49 +00002207_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002208{
2209 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002210 PyObject *op = _PyTrash_delete_later;
2211 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002212
Neil Schemenauerf589c052002-03-29 03:05:54 +00002213 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002214 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002215
Tim Peters803526b2002-07-07 05:13:56 +00002216 /* Call the deallocator directly. This used to try to
2217 * fool Py_DECREF into calling it indirectly, but
2218 * Py_DECREF was already called on this object, and in
2219 * assorted non-release builds calling Py_DECREF again ends
2220 * up distorting allocation statistics.
2221 */
2222 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002223 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002224 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002225 --_PyTrash_delete_nesting;
2226 }
2227}