blob: 9b6a30a4f9799040a8a88ccff574d057ac405c3c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Tim Peters34592512002-07-11 06:23:50 +00006#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +00007Py_ssize_t _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Mark Hammonda2905272002-07-29 13:42:14 +000010int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000011
Guido van Rossum3f5da241990-12-20 15:06:42 +000012/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
13 These are used by the individual routines for object creation.
14 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015
Tim Peters78be7992003-03-23 02:51:01 +000016#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000017/* Head of circular doubly-linked list of all objects. These are linked
18 * together via the _ob_prev and _ob_next members of a PyObject, which
19 * exist only in a Py_TRACE_REFS build.
20 */
Tim Peters78be7992003-03-23 02:51:01 +000021static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000022
Tim Peters7571a0f2003-03-23 17:52:28 +000023/* Insert op at the front of the list of all objects. If force is true,
24 * op is added even if _ob_prev and _ob_next are non-NULL already. If
25 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
26 * force should be true if and only if op points to freshly allocated,
27 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000028 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000029 * Note that objects are normally added to the list via _Py_NewReference,
30 * which is called by PyObject_Init. Not all objects are initialized that
31 * way, though; exceptions include statically allocated type objects, and
32 * statically allocated singletons (like Py_True and Py_None).
33 */
Tim Peters36eb4df2003-03-23 03:33:13 +000034void
Tim Peters7571a0f2003-03-23 17:52:28 +000035_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000036{
Tim Peters7571a0f2003-03-23 17:52:28 +000037#ifdef Py_DEBUG
38 if (!force) {
39 /* If it's initialized memory, op must be in or out of
40 * the list unambiguously.
41 */
42 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
43 }
Tim Peters78be7992003-03-23 02:51:01 +000044#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000045 if (force || op->_ob_prev == NULL) {
46 op->_ob_next = refchain._ob_next;
47 op->_ob_prev = &refchain;
48 refchain._ob_next->_ob_prev = op;
49 refchain._ob_next = op;
50 }
51}
52#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000053
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000054#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000056extern int tuple_zero_allocs, fast_tuple_allocs;
57extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000058extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000059void
Fred Drake100814d2000-07-09 15:48:49 +000060dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000063
64 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000065 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000066 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000067 tp->tp_maxalloc);
68 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
69 fast_tuple_allocs, tuple_zero_allocs);
70 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
71 quick_int_allocs, quick_neg_int_allocs);
72 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
73 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074}
75
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000076PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000077get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000078{
79 PyTypeObject *tp;
80 PyObject *result;
81 PyObject *v;
82
83 result = PyList_New(0);
84 if (result == NULL)
85 return NULL;
86 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
88 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000089 if (v == NULL) {
90 Py_DECREF(result);
91 return NULL;
92 }
93 if (PyList_Append(result, v) < 0) {
94 Py_DECREF(v);
95 Py_DECREF(result);
96 return NULL;
97 }
98 Py_DECREF(v);
99 }
100 return result;
101}
102
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000103void
Fred Drake100814d2000-07-09 15:48:49 +0000104inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000105{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000106 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000107 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000108 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000110 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000111 /* Note that as of Python 2.2, heap-allocated type objects
112 * can go away, but this code requires that they stay alive
113 * until program exit. That's why we're careful with
114 * refcounts here. type_list gets a new reference to tp,
115 * while ownership of the reference type_list used to hold
116 * (if any) was transferred to tp->tp_next in the line above.
117 * tp is thus effectively immortal after this.
118 */
119 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000120 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000121#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000122 /* Also insert in the doubly-linked list of all objects,
123 * if not already there.
124 */
125 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000126#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000128 tp->tp_allocs++;
129 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
130 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000131}
132#endif
133
Tim Peters7c321a82002-07-09 02:57:01 +0000134#ifdef Py_REF_DEBUG
135/* Log a fatal error; doesn't return. */
136void
137_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
138{
139 char buf[300];
140
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000141 /* XXX(twouters) cast refcount to long until %zd is universally
142 available */
Tim Peters7c321a82002-07-09 02:57:01 +0000143 PyOS_snprintf(buf, sizeof(buf),
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000144 "%s:%i object at %p has negative ref count %ld",
145 fname, lineno, op, (long)op->ob_refcnt);
Tim Peters7c321a82002-07-09 02:57:01 +0000146 Py_FatalError(buf);
147}
148
149#endif /* Py_REF_DEBUG */
150
Thomas Heller1328b522004-04-22 17:23:49 +0000151void
152Py_IncRef(PyObject *o)
153{
154 Py_XINCREF(o);
155}
156
157void
158Py_DecRef(PyObject *o)
159{
160 Py_XDECREF(o);
161}
162
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000164PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000166 if (op == NULL)
167 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000168 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171 return op;
172}
173
Guido van Rossumb18618d2000-05-03 23:44:39 +0000174PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000175PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000176{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000177 if (op == NULL)
178 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000179 /* Any changes should be reflected in PyObject_INIT_VAR */
180 op->ob_size = size;
181 op->ob_type = tp;
182 _Py_NewReference((PyObject *)op);
183 return op;
184}
185
186PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000187_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000188{
189 PyObject *op;
190 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
191 if (op == NULL)
192 return PyErr_NoMemory();
193 return PyObject_INIT(op, tp);
194}
195
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000196PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000197_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000199 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000200 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000201 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000203 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000204 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000205}
206
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000207/* for binary compatibility with 2.2 */
208#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000209void
Fred Drake100814d2000-07-09 15:48:49 +0000210_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000211{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000212 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213}
214
Neal Norwitz1a997502003-01-13 20:13:12 +0000215/* Implementation of PyObject_Print with recursion checking */
216static int
217internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218{
Guido van Rossum278ef591991-07-27 21:40:24 +0000219 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000220 if (nesting > 10) {
221 PyErr_SetString(PyExc_RuntimeError, "print recursion");
222 return -1;
223 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000224 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000225 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000226#ifdef USE_STACKCHECK
227 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000228 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000229 return -1;
230 }
231#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000232 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000233 if (op == NULL) {
234 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 }
Guido van Rossum90933611991-06-07 16:10:43 +0000236 else {
237 if (op->ob_refcnt <= 0)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000238 /* XXX(twouters) cast refcount to long until %zd is
239 universally available */
240 fprintf(fp, "<refcnt %ld at %p>",
241 (long)op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000242 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000243 PyObject *s;
244 if (flags & Py_PRINT_RAW)
245 s = PyObject_Str(op);
246 else
247 s = PyObject_Repr(op);
248 if (s == NULL)
249 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000250 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000251 ret = internal_print(s, fp, Py_PRINT_RAW,
252 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000253 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000254 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000255 }
Guido van Rossum90933611991-06-07 16:10:43 +0000256 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000257 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000258 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000259 if (ret == 0) {
260 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000261 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000262 clearerr(fp);
263 ret = -1;
264 }
265 }
266 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267}
268
Neal Norwitz1a997502003-01-13 20:13:12 +0000269int
270PyObject_Print(PyObject *op, FILE *fp, int flags)
271{
272 return internal_print(op, fp, flags, 0);
273}
274
275
Barry Warsaw9bf16442001-01-23 16:24:35 +0000276/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000277void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000278{
Barry Warsaweefb1072001-02-22 22:39:18 +0000279 if (op == NULL)
280 fprintf(stderr, "NULL\n");
281 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000282 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000283 (void)PyObject_Print(op, stderr, 0);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000284 /* XXX(twouters) cast refcount to long until %zd is
285 universally available */
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000286 fprintf(stderr, "\n"
287 "type : %s\n"
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000288 "refcount: %ld\n"
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000289 "address : %p\n",
290 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000291 (long)op->ob_refcnt,
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000292 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000293 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000294}
Barry Warsaw903138f2001-01-23 16:33:18 +0000295
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000297PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000300 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000301#ifdef USE_STACKCHECK
302 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000303 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000304 return NULL;
305 }
306#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000307 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000309 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000310 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000311 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000312 else {
313 PyObject *res;
314 res = (*v->ob_type->tp_repr)(v);
315 if (res == NULL)
316 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000317#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000318 if (PyUnicode_Check(res)) {
319 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000320 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000321 Py_DECREF(res);
322 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000323 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000324 else
325 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000326 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000327#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000328 if (!PyString_Check(res)) {
329 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000330 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000331 res->ob_type->tp_name);
332 Py_DECREF(res);
333 return NULL;
334 }
335 return res;
336 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337}
338
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000340_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000341{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000342 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000343 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000344 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000346 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000347 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000348 return v;
349 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000350#ifdef Py_USING_UNICODE
351 if (PyUnicode_CheckExact(v)) {
352 Py_INCREF(v);
353 return v;
354 }
355#endif
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000356 if (v->ob_type->tp_str == NULL)
357 return PyObject_Repr(v);
358
359 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000360 if (res == NULL)
361 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000362 type_ok = PyString_Check(res);
363#ifdef Py_USING_UNICODE
364 type_ok = type_ok || PyUnicode_Check(res);
365#endif
366 if (!type_ok) {
367 PyErr_Format(PyExc_TypeError,
368 "__str__ returned non-string (type %.200s)",
369 res->ob_type->tp_name);
370 Py_DECREF(res);
371 return NULL;
372 }
373 return res;
374}
375
376PyObject *
377PyObject_Str(PyObject *v)
378{
379 PyObject *res = _PyObject_Str(v);
380 if (res == NULL)
381 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000382#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000383 if (PyUnicode_Check(res)) {
384 PyObject* str;
385 str = PyUnicode_AsEncodedString(res, NULL, NULL);
386 Py_DECREF(res);
387 if (str)
388 res = str;
389 else
390 return NULL;
391 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000392#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +0000393 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000394 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000395}
396
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000397#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000398PyObject *
399PyObject_Unicode(PyObject *v)
400{
401 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000402 PyObject *func;
Neal Norwitz75801462006-03-14 06:02:16 +0000403 PyObject *str;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000404 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000405
Georg Brandl3daf7582006-03-13 22:22:11 +0000406 if (v == NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000407 res = PyString_FromString("<NULL>");
Neal Norwitz75801462006-03-14 06:02:16 +0000408 if (res == NULL)
409 return NULL;
410 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
411 Py_DECREF(res);
412 return str;
Georg Brandl3daf7582006-03-13 22:22:11 +0000413 } else if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000414 Py_INCREF(v);
415 return v;
416 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000417 /* XXX As soon as we have a tp_unicode slot, we should
418 check this before trying the __unicode__
419 method. */
420 if (unicodestr == NULL) {
421 unicodestr= PyString_InternFromString("__unicode__");
422 if (unicodestr == NULL)
423 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000424 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000425 func = PyObject_GetAttr(v, unicodestr);
426 if (func != NULL) {
427 res = PyEval_CallObject(func, (PyObject *)NULL);
428 Py_DECREF(func);
429 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000430 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000431 PyErr_Clear();
432 if (PyUnicode_Check(v)) {
433 /* For a Unicode subtype that's didn't overwrite __unicode__,
434 return a true Unicode object with the same data. */
435 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
436 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000437 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000438 if (PyString_CheckExact(v)) {
439 Py_INCREF(v);
440 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000441 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000442 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000443 if (v->ob_type->tp_str != NULL)
444 res = (*v->ob_type->tp_str)(v);
445 else
446 res = PyObject_Repr(v);
447 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000448 }
449 if (res == NULL)
450 return NULL;
451 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000452 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000453 Py_DECREF(res);
Neal Norwitz75801462006-03-14 06:02:16 +0000454 res = str;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000455 }
456 return res;
457}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000458#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000459
460
Guido van Rossuma4073002002-05-31 20:03:54 +0000461/* Helper to warn about deprecated tp_compare return values. Return:
462 -2 for an exception;
463 -1 if v < w;
464 0 if v == w;
465 1 if v > w.
466 (This function cannot return 2.)
467*/
468static int
469adjust_tp_compare(int c)
470{
471 if (PyErr_Occurred()) {
472 if (c != -1 && c != -2) {
473 PyObject *t, *v, *tb;
474 PyErr_Fetch(&t, &v, &tb);
475 if (PyErr_Warn(PyExc_RuntimeWarning,
476 "tp_compare didn't return -1 or -2 "
477 "for exception") < 0) {
478 Py_XDECREF(t);
479 Py_XDECREF(v);
480 Py_XDECREF(tb);
481 }
482 else
483 PyErr_Restore(t, v, tb);
484 }
485 return -2;
486 }
487 else if (c < -1 || c > 1) {
488 if (PyErr_Warn(PyExc_RuntimeWarning,
489 "tp_compare didn't return -1, 0 or 1") < 0)
490 return -2;
491 else
492 return c < -1 ? -1 : 1;
493 }
494 else {
495 assert(c >= -1 && c <= 1);
496 return c;
497 }
498}
499
500
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000501/* Macro to get the tp_richcompare field of a type if defined */
502#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
503 ? (t)->tp_richcompare : NULL)
504
Guido van Rossume797ec12001-01-17 15:24:28 +0000505/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000506int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000507
Guido van Rossume797ec12001-01-17 15:24:28 +0000508/* Try a genuine rich comparison, returning an object. Return:
509 NULL for exception;
510 NotImplemented if this particular rich comparison is not implemented or
511 undefined;
512 some object not equal to NotImplemented if it is implemented
513 (this latter object may not be a Boolean).
514*/
515static PyObject *
516try_rich_compare(PyObject *v, PyObject *w, int op)
517{
518 richcmpfunc f;
519 PyObject *res;
520
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000521 if (v->ob_type != w->ob_type &&
522 PyType_IsSubtype(w->ob_type, v->ob_type) &&
523 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000524 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000525 if (res != Py_NotImplemented)
526 return res;
527 Py_DECREF(res);
528 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000529 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000530 res = (*f)(v, w, op);
531 if (res != Py_NotImplemented)
532 return res;
533 Py_DECREF(res);
534 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000535 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000536 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000537 }
538 res = Py_NotImplemented;
539 Py_INCREF(res);
540 return res;
541}
542
543/* Try a genuine rich comparison, returning an int. Return:
544 -1 for exception (including the case where try_rich_compare() returns an
545 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000546 0 if the outcome is false;
547 1 if the outcome is true;
548 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000549*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000550static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000551try_rich_compare_bool(PyObject *v, PyObject *w, int op)
552{
553 PyObject *res;
554 int ok;
555
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000556 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000557 return 2; /* Shortcut, avoid INCREF+DECREF */
558 res = try_rich_compare(v, w, op);
559 if (res == NULL)
560 return -1;
561 if (res == Py_NotImplemented) {
562 Py_DECREF(res);
563 return 2;
564 }
565 ok = PyObject_IsTrue(res);
566 Py_DECREF(res);
567 return ok;
568}
569
570/* Try rich comparisons to determine a 3-way comparison. Return:
571 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000572 -1 if v < w;
573 0 if v == w;
574 1 if v > w;
575 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000576*/
577static int
578try_rich_to_3way_compare(PyObject *v, PyObject *w)
579{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000580 static struct { int op; int outcome; } tries[3] = {
581 /* Try this operator, and if it is true, use this outcome: */
582 {Py_EQ, 0},
583 {Py_LT, -1},
584 {Py_GT, 1},
585 };
586 int i;
587
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000588 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000589 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000590
591 for (i = 0; i < 3; i++) {
592 switch (try_rich_compare_bool(v, w, tries[i].op)) {
593 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000594 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000595 case 1:
596 return tries[i].outcome;
597 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000598 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000599
600 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000601}
602
603/* Try a 3-way comparison, returning an int. Return:
604 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000605 -1 if v < w;
606 0 if v == w;
607 1 if v > w;
608 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000609*/
610static int
611try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000612{
613 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000614 cmpfunc f;
615
616 /* Comparisons involving instances are given to instance_compare,
617 which has the same return conventions as this function. */
618
Guido van Rossumab3b0342001-09-18 20:38:53 +0000619 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000620 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000621 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000622 if (PyInstance_Check(w))
623 return (*w->ob_type->tp_compare)(v, w);
624
Guido van Rossumab3b0342001-09-18 20:38:53 +0000625 /* If both have the same (non-NULL) tp_compare, use it. */
626 if (f != NULL && f == w->ob_type->tp_compare) {
627 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000628 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000629 }
630
631 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
632 if (f == _PyObject_SlotCompare ||
633 w->ob_type->tp_compare == _PyObject_SlotCompare)
634 return _PyObject_SlotCompare(v, w);
635
Armin Rigoa1748132004-12-23 22:13:13 +0000636 /* If we're here, v and w,
637 a) are not instances;
638 b) have different types or a type without tp_compare; and
639 c) don't have a user-defined tp_compare.
640 tp_compare implementations in C assume that both arguments
641 have their type, so we give up if the coercion fails or if
642 it yields types which are still incompatible (which can
643 happen with a user-defined nb_coerce).
644 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000645 c = PyNumber_CoerceEx(&v, &w);
646 if (c < 0)
647 return -2;
648 if (c > 0)
649 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000650 f = v->ob_type->tp_compare;
651 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000652 c = (*f)(v, w);
653 Py_DECREF(v);
654 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000655 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000656 }
657
Guido van Rossume797ec12001-01-17 15:24:28 +0000658 /* No comparison defined */
659 Py_DECREF(v);
660 Py_DECREF(w);
661 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000662}
663
Guido van Rossume797ec12001-01-17 15:24:28 +0000664/* Final fallback 3-way comparison, returning an int. Return:
665 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000666 -1 if v < w;
667 0 if v == w;
668 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000669*/
670static int
671default_3way_compare(PyObject *v, PyObject *w)
672{
673 int c;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000674 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000675
676 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000677 /* When comparing these pointers, they must be cast to
678 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
679 * uintptr_t). ANSI specifies that pointer compares other
680 * than == and != to non-related structures are undefined.
681 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000682 Py_uintptr_t vv = (Py_uintptr_t)v;
683 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000684 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
685 }
686
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000687#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000688 /* Special case for Unicode */
689 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
690 c = PyUnicode_Compare(v, w);
691 if (!PyErr_Occurred())
692 return c;
693 /* TypeErrors are ignored: if Unicode coercion fails due
694 to one of the arguments not having the right type, we
695 continue as defined by the coercion protocol (see
696 above). Luckily, decoding errors are reported as
697 ValueErrors and are not masked by this technique. */
698 if (!PyErr_ExceptionMatches(PyExc_TypeError))
699 return -2;
700 PyErr_Clear();
701 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000702#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000703
Guido van Rossum0871e932001-01-22 19:28:09 +0000704 /* None is smaller than anything */
705 if (v == Py_None)
706 return -1;
707 if (w == Py_None)
708 return 1;
709
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000710 /* different type: compare type names; numbers are smaller */
711 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000712 vname = "";
713 else
714 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000715 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000716 wname = "";
717 else
718 wname = w->ob_type->tp_name;
719 c = strcmp(vname, wname);
720 if (c < 0)
721 return -1;
722 if (c > 0)
723 return 1;
724 /* Same type name, or (more likely) incomparable numeric types */
725 return ((Py_uintptr_t)(v->ob_type) < (
726 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000727}
728
Tim Peters6d60b2e2001-05-07 20:53:51 +0000729/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000730 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000731 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000732 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000733 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000734 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000735 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000736*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000737static int
Fred Drake100814d2000-07-09 15:48:49 +0000738do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000739{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000740 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000741 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000742
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000743 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000744 && (f = v->ob_type->tp_compare) != NULL) {
745 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000746 if (PyInstance_Check(v)) {
747 /* Instance tp_compare has a different signature.
748 But if it returns undefined we fall through. */
749 if (c != 2)
750 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000751 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000752 }
753 else
754 return adjust_tp_compare(c);
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000755 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000756 /* We only get here if one of the following is true:
757 a) v and w have different types
758 b) v and w have the same type, which doesn't have tp_compare
759 c) v and w are instances, and either __cmp__ is not defined or
760 __cmp__ returns NotImplemented
761 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000762 c = try_rich_to_3way_compare(v, w);
763 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000764 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000765 c = try_3way_compare(v, w);
766 if (c < 2)
767 return c;
768 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000769}
770
Tim Petersc99213f2001-11-04 05:57:16 +0000771/* Compare v to w. Return
772 -1 if v < w or exception (PyErr_Occurred() true in latter case).
773 0 if v == w.
774 1 if v > w.
775 XXX The docs (C API manual) say the return value is undefined in case
776 XXX of error.
777*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778int
Fred Drake100814d2000-07-09 15:48:49 +0000779PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000781 int result;
782
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000783 if (v == NULL || w == NULL) {
784 PyErr_BadInternalCall();
785 return -1;
786 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000787 if (v == w)
788 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000789 if (Py_EnterRecursiveCall(" in cmp"))
790 return -1;
791 result = do_cmp(v, w);
792 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000793 return result < 0 ? -1 : result;
794}
795
Tim Petersc99213f2001-11-04 05:57:16 +0000796/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000797static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000798convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000799{
Guido van Rossume797ec12001-01-17 15:24:28 +0000800 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000801 switch (op) {
802 case Py_LT: c = c < 0; break;
803 case Py_LE: c = c <= 0; break;
804 case Py_EQ: c = c == 0; break;
805 case Py_NE: c = c != 0; break;
806 case Py_GT: c = c > 0; break;
807 case Py_GE: c = c >= 0; break;
808 }
809 result = c ? Py_True : Py_False;
810 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000811 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
Tim Peters803526b2002-07-07 05:13:56 +0000813
Tim Petersc99213f2001-11-04 05:57:16 +0000814/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
815 Return
816 NULL if error
817 Py_True if v op w
818 Py_False if not (v op w)
819*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000820static PyObject *
821try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
822{
823 int c;
824
825 c = try_3way_compare(v, w);
826 if (c >= 2)
827 c = default_3way_compare(v, w);
828 if (c <= -2)
829 return NULL;
830 return convert_3way_to_object(op, c);
831}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000832
Tim Petersc99213f2001-11-04 05:57:16 +0000833/* Do rich comparison on v and w. Return
834 NULL if error
835 Else a new reference to an object other than Py_NotImplemented, usually(?):
836 Py_True if v op w
837 Py_False if not (v op w)
838*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000839static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000840do_richcmp(PyObject *v, PyObject *w, int op)
841{
842 PyObject *res;
843
844 res = try_rich_compare(v, w, op);
845 if (res != Py_NotImplemented)
846 return res;
847 Py_DECREF(res);
848
849 return try_3way_to_rich_compare(v, w, op);
850}
851
Tim Petersc99213f2001-11-04 05:57:16 +0000852/* Return:
853 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000854 some object not equal to NotImplemented if it is implemented
855 (this latter object may not be a Boolean).
856*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000857PyObject *
858PyObject_RichCompare(PyObject *v, PyObject *w, int op)
859{
860 PyObject *res;
861
862 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000863 if (Py_EnterRecursiveCall(" in cmp"))
864 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000865
Armin Rigo2b3eb402003-10-28 12:05:48 +0000866 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000867 get out cheap (don't bother with coercions etc.). */
868 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
869 cmpfunc fcmp;
870 richcmpfunc frich = RICHCOMPARE(v->ob_type);
871 /* If the type has richcmp, try it first. try_rich_compare
872 tries it two-sided, which is not needed since we've a
873 single type only. */
874 if (frich != NULL) {
875 res = (*frich)(v, w, op);
876 if (res != Py_NotImplemented)
877 goto Done;
878 Py_DECREF(res);
879 }
880 /* No richcmp, or this particular richmp not implemented.
881 Try 3-way cmp. */
882 fcmp = v->ob_type->tp_compare;
883 if (fcmp != NULL) {
884 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000885 c = adjust_tp_compare(c);
886 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000887 res = NULL;
888 goto Done;
889 }
890 res = convert_3way_to_object(op, c);
891 goto Done;
892 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000893 }
Tim Peters67754e92001-11-04 07:29:31 +0000894
895 /* Fast path not taken, or couldn't deliver a useful result. */
896 res = do_richcmp(v, w, op);
897Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000898 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000899 return res;
900}
901
Tim Petersde9725f2001-05-05 10:06:17 +0000902/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000903int
904PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
905{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000906 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000907 int ok;
908
Raymond Hettinger93d44812004-03-21 17:01:44 +0000909 /* Quick result when objects are the same.
910 Guarantees that identity implies equality. */
911 if (v == w) {
912 if (op == Py_EQ)
913 return 1;
914 else if (op == Py_NE)
915 return 0;
916 }
917
918 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000919 if (res == NULL)
920 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000921 if (PyBool_Check(res))
922 ok = (res == Py_True);
923 else
924 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000925 Py_DECREF(res);
926 return ok;
927}
Fred Drake13634cf2000-06-29 19:17:04 +0000928
929/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000930 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000931
932 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
933*/
934
935long
Fred Drake100814d2000-07-09 15:48:49 +0000936_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000937{
Tim Peters39dce292000-08-15 03:34:48 +0000938 double intpart, fractpart;
939 int expo;
940 long hipart;
941 long x; /* the final hash value */
942 /* This is designed so that Python numbers of different types
943 * that compare equal hash to the same value; otherwise comparisons
944 * of mapping keys will turn out weird.
945 */
946
Tim Peters39dce292000-08-15 03:34:48 +0000947 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000948 if (fractpart == 0.0) {
949 /* This must return the same hash as an equal int or long. */
950 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
951 /* Convert to long and use its hash. */
952 PyObject *plong; /* converted to Python long */
953 if (Py_IS_INFINITY(intpart))
954 /* can't convert to long int -- arbitrary */
955 v = v < 0 ? -271828.0 : 314159.0;
956 plong = PyLong_FromDouble(v);
957 if (plong == NULL)
958 return -1;
959 x = PyObject_Hash(plong);
960 Py_DECREF(plong);
961 return x;
962 }
963 /* Fits in a C long == a Python int, so is its own hash. */
964 x = (long)intpart;
965 if (x == -1)
966 x = -2;
967 return x;
968 }
969 /* The fractional part is non-zero, so we don't have to worry about
970 * making this match the hash of some other type.
971 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000972 * Since the VAX D double format has 56 mantissa bits, which is the
973 * most of any double format in use, each of these parts may have as
974 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000975 * So, assuming sizeof(long) >= 4, each part can be broken into two
976 * longs; frexp and multiplication are used to do that.
977 * Also, since the Cray double format has 15 exponent bits, which is
978 * the most of any double format in use, shifting the exponent field
979 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000980 */
Tim Peters39dce292000-08-15 03:34:48 +0000981 v = frexp(v, &expo);
982 v *= 2147483648.0; /* 2**31 */
983 hipart = (long)v; /* take the top 32 bits */
984 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
985 x = hipart + (long)v + (expo << 15);
986 if (x == -1)
987 x = -2;
988 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000989}
990
991long
Fred Drake100814d2000-07-09 15:48:49 +0000992_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000993{
994#if SIZEOF_LONG >= SIZEOF_VOID_P
995 return (long)p;
996#else
997 /* convert to a Python long and hash that */
998 PyObject* longobj;
999 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001000
Fred Drake13634cf2000-06-29 19:17:04 +00001001 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1002 x = -1;
1003 goto finally;
1004 }
1005 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001006
Fred Drake13634cf2000-06-29 19:17:04 +00001007finally:
1008 Py_XDECREF(longobj);
1009 return x;
1010#endif
1011}
1012
1013
Guido van Rossum9bfef441993-03-29 10:43:31 +00001014long
Fred Drake100814d2000-07-09 15:48:49 +00001015PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001016{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001017 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001018 if (tp->tp_hash != NULL)
1019 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001020 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001021 return _Py_HashPointer(v); /* Use address as hash value */
1022 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001023 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001025 return -1;
1026}
1027
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001028PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001029PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001030{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001032
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001034 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 w = PyString_InternFromString(name);
1036 if (w == NULL)
1037 return NULL;
1038 res = PyObject_GetAttr(v, w);
1039 Py_XDECREF(w);
1040 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001041}
1042
1043int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001044PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001045{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001046 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001047 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001048 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001049 return 1;
1050 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001051 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001052 return 0;
1053}
1054
1055int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001056PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001057{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001058 PyObject *s;
1059 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001060
Tim Peters6d6c1a32001-08-02 04:15:00 +00001061 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001062 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 s = PyString_InternFromString(name);
1064 if (s == NULL)
1065 return -1;
1066 res = PyObject_SetAttr(v, s, w);
1067 Py_XDECREF(s);
1068 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001069}
1070
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001071PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001072PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001073{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074 PyTypeObject *tp = v->ob_type;
1075
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001076 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001077#ifdef Py_USING_UNICODE
1078 /* The Unicode to string conversion is done here because the
1079 existing tp_getattro slots expect a string object as name
1080 and we wouldn't want to break those. */
1081 if (PyUnicode_Check(name)) {
1082 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1083 if (name == NULL)
1084 return NULL;
1085 }
1086 else
1087#endif
1088 {
1089 PyErr_SetString(PyExc_TypeError,
1090 "attribute name must be string");
1091 return NULL;
1092 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001093 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094 if (tp->tp_getattro != NULL)
1095 return (*tp->tp_getattro)(v, name);
1096 if (tp->tp_getattr != NULL)
1097 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1098 PyErr_Format(PyExc_AttributeError,
1099 "'%.50s' object has no attribute '%.400s'",
1100 tp->tp_name, PyString_AS_STRING(name));
1101 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001102}
1103
1104int
Fred Drake100814d2000-07-09 15:48:49 +00001105PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001106{
1107 PyObject *res = PyObject_GetAttr(v, name);
1108 if (res != NULL) {
1109 Py_DECREF(res);
1110 return 1;
1111 }
1112 PyErr_Clear();
1113 return 0;
1114}
1115
1116int
Fred Drake100814d2000-07-09 15:48:49 +00001117PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001118{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001120 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001121
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001122 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001123#ifdef Py_USING_UNICODE
1124 /* The Unicode to string conversion is done here because the
1125 existing tp_setattro slots expect a string object as name
1126 and we wouldn't want to break those. */
1127 if (PyUnicode_Check(name)) {
1128 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1129 if (name == NULL)
1130 return -1;
1131 }
Tim Peters803526b2002-07-07 05:13:56 +00001132 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001133#endif
1134 {
1135 PyErr_SetString(PyExc_TypeError,
1136 "attribute name must be string");
1137 return -1;
1138 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001139 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 else
1141 Py_INCREF(name);
1142
1143 PyString_InternInPlace(&name);
1144 if (tp->tp_setattro != NULL) {
1145 err = (*tp->tp_setattro)(v, name, value);
1146 Py_DECREF(name);
1147 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001148 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 if (tp->tp_setattr != NULL) {
1150 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1151 Py_DECREF(name);
1152 return err;
1153 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001154 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1156 PyErr_Format(PyExc_TypeError,
1157 "'%.100s' object has no attributes "
1158 "(%s .%.100s)",
1159 tp->tp_name,
1160 value==NULL ? "del" : "assign to",
1161 PyString_AS_STRING(name));
1162 else
1163 PyErr_Format(PyExc_TypeError,
1164 "'%.100s' object has only read-only attributes "
1165 "(%s .%.100s)",
1166 tp->tp_name,
1167 value==NULL ? "del" : "assign to",
1168 PyString_AS_STRING(name));
1169 return -1;
1170}
1171
1172/* Helper to get a pointer to an object's __dict__ slot, if any */
1173
1174PyObject **
1175_PyObject_GetDictPtr(PyObject *obj)
1176{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001177 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 PyTypeObject *tp = obj->ob_type;
1179
1180 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1181 return NULL;
1182 dictoffset = tp->tp_dictoffset;
1183 if (dictoffset == 0)
1184 return NULL;
1185 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001186 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001187 size_t size;
1188
1189 tsize = ((PyVarObject *)obj)->ob_size;
1190 if (tsize < 0)
1191 tsize = -tsize;
1192 size = _PyObject_VAR_SIZE(tp, tsize);
1193
Tim Peters6d483d32001-10-06 21:27:34 +00001194 dictoffset += (long)size;
1195 assert(dictoffset > 0);
1196 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001197 }
1198 return (PyObject **) ((char *)obj + dictoffset);
1199}
1200
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001202PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001203{
1204 Py_INCREF(obj);
1205 return obj;
1206}
1207
Michael W. Hudson1593f502004-09-14 17:09:47 +00001208/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1209
Raymond Hettinger01538262003-03-17 08:24:35 +00001210PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1212{
1213 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001214 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001215 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001217 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 PyObject **dictptr;
1219
Guido van Rossumebca9fc2001-12-04 15:54:53 +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_setattro slots expect a string object as name
1224 and we wouldn't want to break those. */
1225 if (PyUnicode_Check(name)) {
1226 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1227 if (name == NULL)
1228 return NULL;
1229 }
Tim Peters803526b2002-07-07 05:13:56 +00001230 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001231#endif
1232 {
1233 PyErr_SetString(PyExc_TypeError,
1234 "attribute name must be string");
1235 return NULL;
1236 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001237 }
1238 else
1239 Py_INCREF(name);
1240
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001242 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001243 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 }
1245
Guido van Rossum056fbf42002-08-19 19:22:50 +00001246 /* Inline _PyType_Lookup */
1247 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001248 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001249 PyObject *mro, *base, *dict;
1250
1251 /* Look in tp_dict of types in MRO */
1252 mro = tp->tp_mro;
1253 assert(mro != NULL);
1254 assert(PyTuple_Check(mro));
1255 n = PyTuple_GET_SIZE(mro);
1256 for (i = 0; i < n; i++) {
1257 base = PyTuple_GET_ITEM(mro, i);
1258 if (PyClass_Check(base))
1259 dict = ((PyClassObject *)base)->cl_dict;
1260 else {
1261 assert(PyType_Check(base));
1262 dict = ((PyTypeObject *)base)->tp_dict;
1263 }
1264 assert(dict && PyDict_Check(dict));
1265 descr = PyDict_GetItem(dict, name);
1266 if (descr != NULL)
1267 break;
1268 }
1269 }
1270
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001271 Py_XINCREF(descr);
1272
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001274 if (descr != NULL &&
1275 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001277 if (f != NULL && PyDescr_IsData(descr)) {
1278 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001279 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001280 goto done;
1281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282 }
1283
Guido van Rossumc66ff442002-08-19 16:50:48 +00001284 /* Inline _PyObject_GetDictPtr */
1285 dictoffset = tp->tp_dictoffset;
1286 if (dictoffset != 0) {
1287 PyObject *dict;
1288 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001289 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001290 size_t size;
1291
1292 tsize = ((PyVarObject *)obj)->ob_size;
1293 if (tsize < 0)
1294 tsize = -tsize;
1295 size = _PyObject_VAR_SIZE(tp, tsize);
1296
1297 dictoffset += (long)size;
1298 assert(dictoffset > 0);
1299 assert(dictoffset % SIZEOF_VOID_P == 0);
1300 }
1301 dictptr = (PyObject **) ((char *)obj + dictoffset);
1302 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001304 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305 if (res != NULL) {
1306 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001307 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001308 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309 }
1310 }
1311 }
1312
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001313 if (f != NULL) {
1314 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001315 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001316 goto done;
1317 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318
1319 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001320 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001321 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001322 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 }
1324
1325 PyErr_Format(PyExc_AttributeError,
1326 "'%.50s' object has no attribute '%.400s'",
1327 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001328 done:
1329 Py_DECREF(name);
1330 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331}
1332
1333int
1334PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1335{
1336 PyTypeObject *tp = obj->ob_type;
1337 PyObject *descr;
1338 descrsetfunc f;
1339 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001340 int res = -1;
1341
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001342 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001343#ifdef Py_USING_UNICODE
1344 /* The Unicode to string conversion is done here because the
1345 existing tp_setattro slots expect a string object as name
1346 and we wouldn't want to break those. */
1347 if (PyUnicode_Check(name)) {
1348 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1349 if (name == NULL)
1350 return -1;
1351 }
Tim Peters803526b2002-07-07 05:13:56 +00001352 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001353#endif
1354 {
1355 PyErr_SetString(PyExc_TypeError,
1356 "attribute name must be string");
1357 return -1;
1358 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 }
1360 else
1361 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362
1363 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001364 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001365 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 }
1367
1368 descr = _PyType_Lookup(tp, name);
1369 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001370 if (descr != NULL &&
1371 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001372 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001373 if (f != NULL && PyDescr_IsData(descr)) {
1374 res = f(descr, obj, value);
1375 goto done;
1376 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377 }
1378
1379 dictptr = _PyObject_GetDictPtr(obj);
1380 if (dictptr != NULL) {
1381 PyObject *dict = *dictptr;
1382 if (dict == NULL && value != NULL) {
1383 dict = PyDict_New();
1384 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001385 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 *dictptr = dict;
1387 }
1388 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001389 if (value == NULL)
1390 res = PyDict_DelItem(dict, name);
1391 else
1392 res = PyDict_SetItem(dict, name, value);
1393 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1394 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001395 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001396 }
1397 }
1398
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001399 if (f != NULL) {
1400 res = f(descr, obj, value);
1401 goto done;
1402 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403
1404 if (descr == NULL) {
1405 PyErr_Format(PyExc_AttributeError,
1406 "'%.50s' object has no attribute '%.400s'",
1407 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001408 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 }
1410
1411 PyErr_Format(PyExc_AttributeError,
1412 "'%.50s' object attribute '%.400s' is read-only",
1413 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001414 done:
1415 Py_DECREF(name);
1416 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001417}
1418
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001419/* Test a value used as condition, e.g., in a for or if statement.
1420 Return -1 if an error occurred */
1421
1422int
Fred Drake100814d2000-07-09 15:48:49 +00001423PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001424{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001425 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001426 if (v == Py_True)
1427 return 1;
1428 if (v == Py_False)
1429 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001430 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001431 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001432 else if (v->ob_type->tp_as_number != NULL &&
1433 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001434 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001435 else if (v->ob_type->tp_as_mapping != NULL &&
1436 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001437 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001438 else if (v->ob_type->tp_as_sequence != NULL &&
1439 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001440 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1441 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001442 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443 /* if it is negative, it should be either -1 or -2 */
1444 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001445}
1446
Tim Peters803526b2002-07-07 05:13:56 +00001447/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001448 Return -1 if an error occurred */
1449
1450int
Fred Drake100814d2000-07-09 15:48:49 +00001451PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001452{
1453 int res;
1454 res = PyObject_IsTrue(v);
1455 if (res < 0)
1456 return res;
1457 return res == 0;
1458}
1459
Guido van Rossum5524a591995-01-10 15:26:20 +00001460/* Coerce two numeric types to the "larger" one.
1461 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001462 Return value:
1463 -1 if an error occurred;
1464 0 if the coercion succeeded (and then the reference counts are increased);
1465 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001466*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001467int
Fred Drake100814d2000-07-09 15:48:49 +00001468PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001469{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001470 register PyObject *v = *pv;
1471 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001472 int res;
1473
Guido van Rossum517c7d42002-04-26 02:49:14 +00001474 /* Shortcut only for old-style types */
1475 if (v->ob_type == w->ob_type &&
1476 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1477 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001478 Py_INCREF(v);
1479 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001480 return 0;
1481 }
1482 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1483 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1484 if (res <= 0)
1485 return res;
1486 }
1487 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1488 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1489 if (res <= 0)
1490 return res;
1491 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001492 return 1;
1493}
1494
Guido van Rossume797ec12001-01-17 15:24:28 +00001495/* Coerce two numeric types to the "larger" one.
1496 Increment the reference count on each argument.
1497 Return -1 and raise an exception if no coercion is possible
1498 (and then no reference count is incremented).
1499*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001500int
Fred Drake100814d2000-07-09 15:48:49 +00001501PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001502{
1503 int err = PyNumber_CoerceEx(pv, pw);
1504 if (err <= 0)
1505 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001506 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001507 return -1;
1508}
1509
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001510
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001511/* Test whether an object can be called */
1512
1513int
Fred Drake100814d2000-07-09 15:48:49 +00001514PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001515{
1516 if (x == NULL)
1517 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001518 if (PyInstance_Check(x)) {
1519 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001520 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001521 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001522 return 0;
1523 }
1524 /* Could test recursively but don't, for fear of endless
1525 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001526 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001527 return 1;
1528 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529 else {
1530 return x->ob_type->tp_call != NULL;
1531 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001532}
1533
Tim Peters7eea37e2001-09-04 22:08:56 +00001534/* Helper for PyObject_Dir.
1535 Merge the __dict__ of aclass into dict, and recursively also all
1536 the __dict__s of aclass's base classes. The order of merging isn't
1537 defined, as it's expected that only the final set of dict keys is
1538 interesting.
1539 Return 0 on success, -1 on error.
1540*/
1541
1542static int
1543merge_class_dict(PyObject* dict, PyObject* aclass)
1544{
1545 PyObject *classdict;
1546 PyObject *bases;
1547
1548 assert(PyDict_Check(dict));
1549 assert(aclass);
1550
1551 /* Merge in the type's dict (if any). */
1552 classdict = PyObject_GetAttrString(aclass, "__dict__");
1553 if (classdict == NULL)
1554 PyErr_Clear();
1555 else {
1556 int status = PyDict_Update(dict, classdict);
1557 Py_DECREF(classdict);
1558 if (status < 0)
1559 return -1;
1560 }
1561
1562 /* Recursively merge in the base types' (if any) dicts. */
1563 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001564 if (bases == NULL)
1565 PyErr_Clear();
1566 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001567 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001568 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001569 n = PySequence_Size(bases); /* This better be right */
1570 if (n < 0)
1571 PyErr_Clear();
1572 else {
1573 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001574 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001575 PyObject *base = PySequence_GetItem(bases, i);
1576 if (base == NULL) {
1577 Py_DECREF(bases);
1578 return -1;
1579 }
Tim Peters18e70832003-02-05 19:35:19 +00001580 status = merge_class_dict(dict, base);
1581 Py_DECREF(base);
1582 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001583 Py_DECREF(bases);
1584 return -1;
1585 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001586 }
1587 }
1588 Py_DECREF(bases);
1589 }
1590 return 0;
1591}
1592
Tim Peters305b5852001-09-17 02:38:46 +00001593/* Helper for PyObject_Dir.
1594 If obj has an attr named attrname that's a list, merge its string
1595 elements into keys of dict.
1596 Return 0 on success, -1 on error. Errors due to not finding the attr,
1597 or the attr not being a list, are suppressed.
1598*/
1599
1600static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001601merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001602{
1603 PyObject *list;
1604 int result = 0;
1605
1606 assert(PyDict_Check(dict));
1607 assert(obj);
1608 assert(attrname);
1609
1610 list = PyObject_GetAttrString(obj, attrname);
1611 if (list == NULL)
1612 PyErr_Clear();
1613
1614 else if (PyList_Check(list)) {
1615 int i;
1616 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1617 PyObject *item = PyList_GET_ITEM(list, i);
1618 if (PyString_Check(item)) {
1619 result = PyDict_SetItem(dict, item, Py_None);
1620 if (result < 0)
1621 break;
1622 }
1623 }
1624 }
1625
1626 Py_XDECREF(list);
1627 return result;
1628}
1629
Tim Peters7eea37e2001-09-04 22:08:56 +00001630/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1631 docstring, which should be kept in synch with this implementation. */
1632
1633PyObject *
1634PyObject_Dir(PyObject *arg)
1635{
1636 /* Set exactly one of these non-NULL before the end. */
1637 PyObject *result = NULL; /* result list */
1638 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1639
1640 /* If NULL arg, return the locals. */
1641 if (arg == NULL) {
1642 PyObject *locals = PyEval_GetLocals();
1643 if (locals == NULL)
1644 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001645 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001646 if (result == NULL)
1647 goto error;
1648 }
1649
1650 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001651 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001652 masterdict = PyObject_GetAttrString(arg, "__dict__");
1653 if (masterdict == NULL)
1654 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001655 if (!PyDict_Check(masterdict)) {
1656 PyErr_SetString(PyExc_TypeError,
1657 "module.__dict__ is not a dictionary");
1658 goto error;
1659 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001660 }
1661
1662 /* Elif some form of type or class, grab its dict and its bases.
1663 We deliberately don't suck up its __class__, as methods belonging
1664 to the metaclass would probably be more confusing than helpful. */
1665 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1666 masterdict = PyDict_New();
1667 if (masterdict == NULL)
1668 goto error;
1669 if (merge_class_dict(masterdict, arg) < 0)
1670 goto error;
1671 }
1672
1673 /* Else look at its dict, and the attrs reachable from its class. */
1674 else {
1675 PyObject *itsclass;
1676 /* Create a dict to start with. CAUTION: Not everything
1677 responding to __dict__ returns a dict! */
1678 masterdict = PyObject_GetAttrString(arg, "__dict__");
1679 if (masterdict == NULL) {
1680 PyErr_Clear();
1681 masterdict = PyDict_New();
1682 }
1683 else if (!PyDict_Check(masterdict)) {
1684 Py_DECREF(masterdict);
1685 masterdict = PyDict_New();
1686 }
1687 else {
1688 /* The object may have returned a reference to its
1689 dict, so copy it to avoid mutating it. */
1690 PyObject *temp = PyDict_Copy(masterdict);
1691 Py_DECREF(masterdict);
1692 masterdict = temp;
1693 }
1694 if (masterdict == NULL)
1695 goto error;
1696
Tim Peters305b5852001-09-17 02:38:46 +00001697 /* Merge in __members__ and __methods__ (if any).
1698 XXX Would like this to go away someday; for now, it's
1699 XXX needed to get at im_self etc of method objects. */
1700 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1701 goto error;
1702 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1703 goto error;
1704
Tim Peters7eea37e2001-09-04 22:08:56 +00001705 /* Merge in attrs reachable from its class.
1706 CAUTION: Not all objects have a __class__ attr. */
1707 itsclass = PyObject_GetAttrString(arg, "__class__");
1708 if (itsclass == NULL)
1709 PyErr_Clear();
1710 else {
1711 int status = merge_class_dict(masterdict, itsclass);
1712 Py_DECREF(itsclass);
1713 if (status < 0)
1714 goto error;
1715 }
1716 }
1717
1718 assert((result == NULL) ^ (masterdict == NULL));
1719 if (masterdict != NULL) {
1720 /* The result comes from its keys. */
1721 assert(result == NULL);
1722 result = PyDict_Keys(masterdict);
1723 if (result == NULL)
1724 goto error;
1725 }
1726
1727 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001728 if (!PyList_Check(result)) {
Tim Petersf4aca752004-09-23 02:39:37 +00001729 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001730 "Expected keys() to be a list.");
1731 goto error;
1732 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001733 if (PyList_Sort(result) != 0)
1734 goto error;
1735 else
1736 goto normal_return;
1737
1738 error:
1739 Py_XDECREF(result);
1740 result = NULL;
1741 /* fall through */
1742 normal_return:
1743 Py_XDECREF(masterdict);
1744 return result;
1745}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001746
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001747/*
1748NoObject is usable as a non-NULL undefined value, used by the macro None.
1749There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001750so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001751(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001752*/
1753
Guido van Rossum0c182a11992-03-27 17:26:13 +00001754/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001755static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001756none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001757{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001758 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001759}
1760
Barry Warsaw9bf16442001-01-23 16:24:35 +00001761/* ARGUSED */
1762static void
Tim Peters803526b2002-07-07 05:13:56 +00001763none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001764{
1765 /* This should never get called, but we also don't want to SEGV if
1766 * we accidently decref None out of existance.
1767 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001768 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001769}
1770
1771
Guido van Rossumba21a492001-08-16 08:17:26 +00001772static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001773 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001774 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001775 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001776 0,
1777 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001778 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001779 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001780 0, /*tp_getattr*/
1781 0, /*tp_setattr*/
1782 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001783 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001784 0, /*tp_as_number*/
1785 0, /*tp_as_sequence*/
1786 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001787 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001788};
1789
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001790PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001791 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001792};
1793
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001794/* NotImplemented is an object that can be used to signal that an
1795 operation is not implemented for the given type combination. */
1796
1797static PyObject *
1798NotImplemented_repr(PyObject *op)
1799{
1800 return PyString_FromString("NotImplemented");
1801}
1802
1803static PyTypeObject PyNotImplemented_Type = {
1804 PyObject_HEAD_INIT(&PyType_Type)
1805 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001806 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001807 0,
1808 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001809 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001810 0, /*tp_print*/
1811 0, /*tp_getattr*/
1812 0, /*tp_setattr*/
1813 0, /*tp_compare*/
1814 (reprfunc)NotImplemented_repr, /*tp_repr*/
1815 0, /*tp_as_number*/
1816 0, /*tp_as_sequence*/
1817 0, /*tp_as_mapping*/
1818 0, /*tp_hash */
1819};
1820
1821PyObject _Py_NotImplementedStruct = {
1822 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1823};
1824
Guido van Rossumba21a492001-08-16 08:17:26 +00001825void
1826_Py_ReadyTypes(void)
1827{
1828 if (PyType_Ready(&PyType_Type) < 0)
1829 Py_FatalError("Can't initialize 'type'");
1830
Fred Drake0a4dd392004-07-02 18:57:45 +00001831 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1832 Py_FatalError("Can't initialize 'weakref'");
1833
Guido van Rossum77f6a652002-04-03 22:41:51 +00001834 if (PyType_Ready(&PyBool_Type) < 0)
1835 Py_FatalError("Can't initialize 'bool'");
1836
Guido van Rossumcacfc072002-05-24 19:01:59 +00001837 if (PyType_Ready(&PyString_Type) < 0)
1838 Py_FatalError("Can't initialize 'str'");
1839
Guido van Rossumba21a492001-08-16 08:17:26 +00001840 if (PyType_Ready(&PyList_Type) < 0)
1841 Py_FatalError("Can't initialize 'list'");
1842
1843 if (PyType_Ready(&PyNone_Type) < 0)
1844 Py_FatalError("Can't initialize type(None)");
1845
1846 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1847 Py_FatalError("Can't initialize type(NotImplemented)");
1848}
1849
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001850
Guido van Rossum84a90321996-05-22 16:34:47 +00001851#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001852
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001853void
Fred Drake100814d2000-07-09 15:48:49 +00001854_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001855{
Tim Peters34592512002-07-11 06:23:50 +00001856 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001857 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001858 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001859 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001860}
1861
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001862void
Fred Drake100814d2000-07-09 15:48:49 +00001863_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001864{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001865#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001866 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001867#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001868 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001869 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001870 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001871 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001872 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001873#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001874 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1875 if (p == op)
1876 break;
1877 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001878 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001879 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001880#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001881 op->_ob_next->_ob_prev = op->_ob_prev;
1882 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001883 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001884 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001885}
1886
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001887void
Fred Drake100814d2000-07-09 15:48:49 +00001888_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001889{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001890 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001891 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001892 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001893}
1894
Tim Peters269b2a62003-04-17 19:52:29 +00001895/* Print all live objects. Because PyObject_Print is called, the
1896 * interpreter must be in a healthy state.
1897 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001898void
Fred Drake100814d2000-07-09 15:48:49 +00001899_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001900{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001901 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001902 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001903 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001904 /* XXX(twouters) cast refcount to long until %zd is
1905 universally available */
1906 fprintf(fp, "%p [%ld] ", op, (long)op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001907 if (PyObject_Print(op, fp, 0) != 0)
1908 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001909 putc('\n', fp);
1910 }
1911}
1912
Tim Peters269b2a62003-04-17 19:52:29 +00001913/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1914 * doesn't make any calls to the Python C API, so is always safe to call.
1915 */
1916void
1917_Py_PrintReferenceAddresses(FILE *fp)
1918{
1919 PyObject *op;
1920 fprintf(fp, "Remaining object addresses:\n");
1921 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001922 /* XXX(twouters) cast refcount to long until %zd is
1923 universally available */
1924 fprintf(fp, "%p [%ld] %s\n", op, (long)op->ob_refcnt,
Tim Peters21d7d4d2003-04-18 00:45:59 +00001925 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001926}
1927
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001928PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001929_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001930{
1931 int i, n;
1932 PyObject *t = NULL;
1933 PyObject *res, *op;
1934
1935 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1936 return NULL;
1937 op = refchain._ob_next;
1938 res = PyList_New(0);
1939 if (res == NULL)
1940 return NULL;
1941 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1942 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001943 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001944 op = op->_ob_next;
1945 if (op == &refchain)
1946 return res;
1947 }
1948 if (PyList_Append(res, op) < 0) {
1949 Py_DECREF(res);
1950 return NULL;
1951 }
1952 op = op->_ob_next;
1953 }
1954 return res;
1955}
1956
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001957#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001958
1959
1960/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001961PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001962
1963
1964/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001965Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001966
1967
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001968/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001969
Thomas Wouters334fb892000-07-25 12:56:38 +00001970void *
Fred Drake100814d2000-07-09 15:48:49 +00001971PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001972{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001973 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001974}
1975
Thomas Wouters334fb892000-07-25 12:56:38 +00001976void *
1977PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001978{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001979 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001980}
1981
1982void
Thomas Wouters334fb892000-07-25 12:56:38 +00001983PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001984{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001985 PyMem_FREE(p);
1986}
1987
1988
Guido van Rossum86610361998-04-10 22:32:46 +00001989/* These methods are used to control infinite recursion in repr, str, print,
1990 etc. Container objects that may recursively contain themselves,
1991 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1992 Py_ReprLeave() to avoid infinite recursion.
1993
1994 Py_ReprEnter() returns 0 the first time it is called for a particular
1995 object and 1 every time thereafter. It returns -1 if an exception
1996 occurred. Py_ReprLeave() has no return value.
1997
1998 See dictobject.c and listobject.c for examples of use.
1999*/
2000
2001#define KEY "Py_Repr"
2002
2003int
Fred Drake100814d2000-07-09 15:48:49 +00002004Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002005{
2006 PyObject *dict;
2007 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002008 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002009
2010 dict = PyThreadState_GetDict();
2011 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00002012 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002013 list = PyDict_GetItemString(dict, KEY);
2014 if (list == NULL) {
2015 list = PyList_New(0);
2016 if (list == NULL)
2017 return -1;
2018 if (PyDict_SetItemString(dict, KEY, list) < 0)
2019 return -1;
2020 Py_DECREF(list);
2021 }
2022 i = PyList_GET_SIZE(list);
2023 while (--i >= 0) {
2024 if (PyList_GET_ITEM(list, i) == obj)
2025 return 1;
2026 }
2027 PyList_Append(list, obj);
2028 return 0;
2029}
2030
2031void
Fred Drake100814d2000-07-09 15:48:49 +00002032Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002033{
2034 PyObject *dict;
2035 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002036 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002037
2038 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002039 if (dict == NULL)
2040 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002041 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002042 if (list == NULL || !PyList_Check(list))
2043 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002044 i = PyList_GET_SIZE(list);
2045 /* Count backwards because we always expect obj to be list[-1] */
2046 while (--i >= 0) {
2047 if (PyList_GET_ITEM(list, i) == obj) {
2048 PyList_SetSlice(list, i, i + 1, NULL);
2049 break;
2050 }
2051 }
2052}
Guido van Rossumd724b232000-03-13 16:01:29 +00002053
Tim Peters803526b2002-07-07 05:13:56 +00002054/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002055
Tim Peters803526b2002-07-07 05:13:56 +00002056/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002057int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002058
Tim Peters803526b2002-07-07 05:13:56 +00002059/* List of objects that still need to be cleaned up, singly linked via their
2060 * gc headers' gc_prev pointers.
2061 */
2062PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002063
Tim Peters803526b2002-07-07 05:13:56 +00002064/* Add op to the _PyTrash_delete_later list. Called when the current
2065 * call-stack depth gets large. op must be a currently untracked gc'ed
2066 * object, with refcount 0. Py_DECREF must already have been called on it.
2067 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002068void
Fred Drake100814d2000-07-09 15:48:49 +00002069_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002070{
Tim Peters803526b2002-07-07 05:13:56 +00002071 assert(PyObject_IS_GC(op));
2072 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2073 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002074 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002075 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002076}
2077
Tim Peters803526b2002-07-07 05:13:56 +00002078/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2079 * the call-stack unwinds again.
2080 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002081void
Fred Drake100814d2000-07-09 15:48:49 +00002082_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002083{
2084 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002085 PyObject *op = _PyTrash_delete_later;
2086 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002087
Neil Schemenauerf589c052002-03-29 03:05:54 +00002088 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002089 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002090
Tim Peters803526b2002-07-07 05:13:56 +00002091 /* Call the deallocator directly. This used to try to
2092 * fool Py_DECREF into calling it indirectly, but
2093 * Py_DECREF was already called on this object, and in
2094 * assorted non-release builds calling Py_DECREF again ends
2095 * up distorting allocation statistics.
2096 */
2097 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002098 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002099 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002100 --_PyTrash_delete_nesting;
2101 }
2102}