blob: 866ce068c2091db5c4208dbe6464ca45a78ea8fc [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;
403 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000404
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000405 if (v == NULL)
406 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000407 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000408 Py_INCREF(v);
409 return v;
410 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000411 /* XXX As soon as we have a tp_unicode slot, we should
412 check this before trying the __unicode__
413 method. */
414 if (unicodestr == NULL) {
415 unicodestr= PyString_InternFromString("__unicode__");
416 if (unicodestr == NULL)
417 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000418 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000419 func = PyObject_GetAttr(v, unicodestr);
420 if (func != NULL) {
421 res = PyEval_CallObject(func, (PyObject *)NULL);
422 Py_DECREF(func);
423 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000424 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000425 PyErr_Clear();
426 if (PyUnicode_Check(v)) {
427 /* For a Unicode subtype that's didn't overwrite __unicode__,
428 return a true Unicode object with the same data. */
429 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
430 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000431 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000432 if (PyString_CheckExact(v)) {
433 Py_INCREF(v);
434 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000435 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000436 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000437 if (v->ob_type->tp_str != NULL)
438 res = (*v->ob_type->tp_str)(v);
439 else
440 res = PyObject_Repr(v);
441 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000442 }
443 if (res == NULL)
444 return NULL;
445 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000446 PyObject *str;
447 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000448 Py_DECREF(res);
449 if (str)
450 res = str;
451 else
Brett Cannonc3647ac2005-04-26 03:45:26 +0000452 return NULL;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000453 }
454 return res;
455}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000456#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000457
458
Guido van Rossuma4073002002-05-31 20:03:54 +0000459/* Helper to warn about deprecated tp_compare return values. Return:
460 -2 for an exception;
461 -1 if v < w;
462 0 if v == w;
463 1 if v > w.
464 (This function cannot return 2.)
465*/
466static int
467adjust_tp_compare(int c)
468{
469 if (PyErr_Occurred()) {
470 if (c != -1 && c != -2) {
471 PyObject *t, *v, *tb;
472 PyErr_Fetch(&t, &v, &tb);
473 if (PyErr_Warn(PyExc_RuntimeWarning,
474 "tp_compare didn't return -1 or -2 "
475 "for exception") < 0) {
476 Py_XDECREF(t);
477 Py_XDECREF(v);
478 Py_XDECREF(tb);
479 }
480 else
481 PyErr_Restore(t, v, tb);
482 }
483 return -2;
484 }
485 else if (c < -1 || c > 1) {
486 if (PyErr_Warn(PyExc_RuntimeWarning,
487 "tp_compare didn't return -1, 0 or 1") < 0)
488 return -2;
489 else
490 return c < -1 ? -1 : 1;
491 }
492 else {
493 assert(c >= -1 && c <= 1);
494 return c;
495 }
496}
497
498
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000499/* Macro to get the tp_richcompare field of a type if defined */
500#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
501 ? (t)->tp_richcompare : NULL)
502
Guido van Rossume797ec12001-01-17 15:24:28 +0000503/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000504int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000505
Guido van Rossume797ec12001-01-17 15:24:28 +0000506/* Try a genuine rich comparison, returning an object. Return:
507 NULL for exception;
508 NotImplemented if this particular rich comparison is not implemented or
509 undefined;
510 some object not equal to NotImplemented if it is implemented
511 (this latter object may not be a Boolean).
512*/
513static PyObject *
514try_rich_compare(PyObject *v, PyObject *w, int op)
515{
516 richcmpfunc f;
517 PyObject *res;
518
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000519 if (v->ob_type != w->ob_type &&
520 PyType_IsSubtype(w->ob_type, v->ob_type) &&
521 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000522 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000523 if (res != Py_NotImplemented)
524 return res;
525 Py_DECREF(res);
526 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000527 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000528 res = (*f)(v, w, op);
529 if (res != Py_NotImplemented)
530 return res;
531 Py_DECREF(res);
532 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000533 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000534 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000535 }
536 res = Py_NotImplemented;
537 Py_INCREF(res);
538 return res;
539}
540
541/* Try a genuine rich comparison, returning an int. Return:
542 -1 for exception (including the case where try_rich_compare() returns an
543 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000544 0 if the outcome is false;
545 1 if the outcome is true;
546 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000547*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000548static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000549try_rich_compare_bool(PyObject *v, PyObject *w, int op)
550{
551 PyObject *res;
552 int ok;
553
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000554 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000555 return 2; /* Shortcut, avoid INCREF+DECREF */
556 res = try_rich_compare(v, w, op);
557 if (res == NULL)
558 return -1;
559 if (res == Py_NotImplemented) {
560 Py_DECREF(res);
561 return 2;
562 }
563 ok = PyObject_IsTrue(res);
564 Py_DECREF(res);
565 return ok;
566}
567
568/* Try rich comparisons to determine a 3-way comparison. 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 rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000574*/
575static int
576try_rich_to_3way_compare(PyObject *v, PyObject *w)
577{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000578 static struct { int op; int outcome; } tries[3] = {
579 /* Try this operator, and if it is true, use this outcome: */
580 {Py_EQ, 0},
581 {Py_LT, -1},
582 {Py_GT, 1},
583 };
584 int i;
585
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000586 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000587 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000588
589 for (i = 0; i < 3; i++) {
590 switch (try_rich_compare_bool(v, w, tries[i].op)) {
591 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000592 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000593 case 1:
594 return tries[i].outcome;
595 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000596 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000597
598 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000599}
600
601/* Try a 3-way comparison, returning an int. Return:
602 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000603 -1 if v < w;
604 0 if v == w;
605 1 if v > w;
606 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000607*/
608static int
609try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000610{
611 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000612 cmpfunc f;
613
614 /* Comparisons involving instances are given to instance_compare,
615 which has the same return conventions as this function. */
616
Guido van Rossumab3b0342001-09-18 20:38:53 +0000617 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000618 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000619 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000620 if (PyInstance_Check(w))
621 return (*w->ob_type->tp_compare)(v, w);
622
Guido van Rossumab3b0342001-09-18 20:38:53 +0000623 /* If both have the same (non-NULL) tp_compare, use it. */
624 if (f != NULL && f == w->ob_type->tp_compare) {
625 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000626 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000627 }
628
629 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
630 if (f == _PyObject_SlotCompare ||
631 w->ob_type->tp_compare == _PyObject_SlotCompare)
632 return _PyObject_SlotCompare(v, w);
633
Armin Rigoa1748132004-12-23 22:13:13 +0000634 /* If we're here, v and w,
635 a) are not instances;
636 b) have different types or a type without tp_compare; and
637 c) don't have a user-defined tp_compare.
638 tp_compare implementations in C assume that both arguments
639 have their type, so we give up if the coercion fails or if
640 it yields types which are still incompatible (which can
641 happen with a user-defined nb_coerce).
642 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000643 c = PyNumber_CoerceEx(&v, &w);
644 if (c < 0)
645 return -2;
646 if (c > 0)
647 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000648 f = v->ob_type->tp_compare;
649 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000650 c = (*f)(v, w);
651 Py_DECREF(v);
652 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000653 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000654 }
655
Guido van Rossume797ec12001-01-17 15:24:28 +0000656 /* No comparison defined */
657 Py_DECREF(v);
658 Py_DECREF(w);
659 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000660}
661
Guido van Rossume797ec12001-01-17 15:24:28 +0000662/* Final fallback 3-way comparison, returning an int. Return:
663 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000664 -1 if v < w;
665 0 if v == w;
666 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000667*/
668static int
669default_3way_compare(PyObject *v, PyObject *w)
670{
671 int c;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000672 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000673
674 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000675 /* When comparing these pointers, they must be cast to
676 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
677 * uintptr_t). ANSI specifies that pointer compares other
678 * than == and != to non-related structures are undefined.
679 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000680 Py_uintptr_t vv = (Py_uintptr_t)v;
681 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000682 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
683 }
684
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000685#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000686 /* Special case for Unicode */
687 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
688 c = PyUnicode_Compare(v, w);
689 if (!PyErr_Occurred())
690 return c;
691 /* TypeErrors are ignored: if Unicode coercion fails due
692 to one of the arguments not having the right type, we
693 continue as defined by the coercion protocol (see
694 above). Luckily, decoding errors are reported as
695 ValueErrors and are not masked by this technique. */
696 if (!PyErr_ExceptionMatches(PyExc_TypeError))
697 return -2;
698 PyErr_Clear();
699 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000700#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000701
Guido van Rossum0871e932001-01-22 19:28:09 +0000702 /* None is smaller than anything */
703 if (v == Py_None)
704 return -1;
705 if (w == Py_None)
706 return 1;
707
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000708 /* different type: compare type names; numbers are smaller */
709 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000710 vname = "";
711 else
712 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000713 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000714 wname = "";
715 else
716 wname = w->ob_type->tp_name;
717 c = strcmp(vname, wname);
718 if (c < 0)
719 return -1;
720 if (c > 0)
721 return 1;
722 /* Same type name, or (more likely) incomparable numeric types */
723 return ((Py_uintptr_t)(v->ob_type) < (
724 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000725}
726
Tim Peters6d60b2e2001-05-07 20:53:51 +0000727/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000728 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000729 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000730 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000731 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000732 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000733 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000734*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000735static int
Fred Drake100814d2000-07-09 15:48:49 +0000736do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000737{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000738 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000739 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000740
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000741 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000742 && (f = v->ob_type->tp_compare) != NULL) {
743 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000744 if (PyInstance_Check(v)) {
745 /* Instance tp_compare has a different signature.
746 But if it returns undefined we fall through. */
747 if (c != 2)
748 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000749 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000750 }
751 else
752 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000753 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000754 /* We only get here if one of the following is true:
755 a) v and w have different types
756 b) v and w have the same type, which doesn't have tp_compare
757 c) v and w are instances, and either __cmp__ is not defined or
758 __cmp__ returns NotImplemented
759 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000760 c = try_rich_to_3way_compare(v, w);
761 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000762 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000763 c = try_3way_compare(v, w);
764 if (c < 2)
765 return c;
766 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000767}
768
Tim Petersc99213f2001-11-04 05:57:16 +0000769/* Compare v to w. Return
770 -1 if v < w or exception (PyErr_Occurred() true in latter case).
771 0 if v == w.
772 1 if v > w.
773 XXX The docs (C API manual) say the return value is undefined in case
774 XXX of error.
775*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000776int
Fred Drake100814d2000-07-09 15:48:49 +0000777PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000779 int result;
780
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000781 if (v == NULL || w == NULL) {
782 PyErr_BadInternalCall();
783 return -1;
784 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000785 if (v == w)
786 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000787 if (Py_EnterRecursiveCall(" in cmp"))
788 return -1;
789 result = do_cmp(v, w);
790 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000791 return result < 0 ? -1 : result;
792}
793
Tim Petersc99213f2001-11-04 05:57:16 +0000794/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000795static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000796convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000797{
Guido van Rossume797ec12001-01-17 15:24:28 +0000798 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000799 switch (op) {
800 case Py_LT: c = c < 0; break;
801 case Py_LE: c = c <= 0; break;
802 case Py_EQ: c = c == 0; break;
803 case Py_NE: c = c != 0; break;
804 case Py_GT: c = c > 0; break;
805 case Py_GE: c = c >= 0; break;
806 }
807 result = c ? Py_True : Py_False;
808 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000809 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810}
Tim Peters803526b2002-07-07 05:13:56 +0000811
Tim Petersc99213f2001-11-04 05:57:16 +0000812/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
813 Return
814 NULL if error
815 Py_True if v op w
816 Py_False if not (v op w)
817*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000818static PyObject *
819try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
820{
821 int c;
822
823 c = try_3way_compare(v, w);
824 if (c >= 2)
825 c = default_3way_compare(v, w);
826 if (c <= -2)
827 return NULL;
828 return convert_3way_to_object(op, c);
829}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000830
Tim Petersc99213f2001-11-04 05:57:16 +0000831/* Do rich comparison on v and w. Return
832 NULL if error
833 Else a new reference to an object other than Py_NotImplemented, usually(?):
834 Py_True if v op w
835 Py_False if not (v op w)
836*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000837static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000838do_richcmp(PyObject *v, PyObject *w, int op)
839{
840 PyObject *res;
841
842 res = try_rich_compare(v, w, op);
843 if (res != Py_NotImplemented)
844 return res;
845 Py_DECREF(res);
846
847 return try_3way_to_rich_compare(v, w, op);
848}
849
Tim Petersc99213f2001-11-04 05:57:16 +0000850/* Return:
851 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000852 some object not equal to NotImplemented if it is implemented
853 (this latter object may not be a Boolean).
854*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000855PyObject *
856PyObject_RichCompare(PyObject *v, PyObject *w, int op)
857{
858 PyObject *res;
859
860 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000861 if (Py_EnterRecursiveCall(" in cmp"))
862 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000863
Armin Rigo2b3eb402003-10-28 12:05:48 +0000864 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000865 get out cheap (don't bother with coercions etc.). */
866 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
867 cmpfunc fcmp;
868 richcmpfunc frich = RICHCOMPARE(v->ob_type);
869 /* If the type has richcmp, try it first. try_rich_compare
870 tries it two-sided, which is not needed since we've a
871 single type only. */
872 if (frich != NULL) {
873 res = (*frich)(v, w, op);
874 if (res != Py_NotImplemented)
875 goto Done;
876 Py_DECREF(res);
877 }
878 /* No richcmp, or this particular richmp not implemented.
879 Try 3-way cmp. */
880 fcmp = v->ob_type->tp_compare;
881 if (fcmp != NULL) {
882 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000883 c = adjust_tp_compare(c);
884 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000885 res = NULL;
886 goto Done;
887 }
888 res = convert_3way_to_object(op, c);
889 goto Done;
890 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000891 }
Tim Peters67754e92001-11-04 07:29:31 +0000892
893 /* Fast path not taken, or couldn't deliver a useful result. */
894 res = do_richcmp(v, w, op);
895Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000896 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000897 return res;
898}
899
Tim Petersde9725f2001-05-05 10:06:17 +0000900/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000901int
902PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
903{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000904 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000905 int ok;
906
Raymond Hettinger93d44812004-03-21 17:01:44 +0000907 /* Quick result when objects are the same.
908 Guarantees that identity implies equality. */
909 if (v == w) {
910 if (op == Py_EQ)
911 return 1;
912 else if (op == Py_NE)
913 return 0;
914 }
915
916 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000917 if (res == NULL)
918 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000919 if (PyBool_Check(res))
920 ok = (res == Py_True);
921 else
922 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000923 Py_DECREF(res);
924 return ok;
925}
Fred Drake13634cf2000-06-29 19:17:04 +0000926
927/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000928 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000929
930 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
931*/
932
933long
Fred Drake100814d2000-07-09 15:48:49 +0000934_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000935{
Tim Peters39dce292000-08-15 03:34:48 +0000936 double intpart, fractpart;
937 int expo;
938 long hipart;
939 long x; /* the final hash value */
940 /* This is designed so that Python numbers of different types
941 * that compare equal hash to the same value; otherwise comparisons
942 * of mapping keys will turn out weird.
943 */
944
Tim Peters39dce292000-08-15 03:34:48 +0000945 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000946 if (fractpart == 0.0) {
947 /* This must return the same hash as an equal int or long. */
948 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
949 /* Convert to long and use its hash. */
950 PyObject *plong; /* converted to Python long */
951 if (Py_IS_INFINITY(intpart))
952 /* can't convert to long int -- arbitrary */
953 v = v < 0 ? -271828.0 : 314159.0;
954 plong = PyLong_FromDouble(v);
955 if (plong == NULL)
956 return -1;
957 x = PyObject_Hash(plong);
958 Py_DECREF(plong);
959 return x;
960 }
961 /* Fits in a C long == a Python int, so is its own hash. */
962 x = (long)intpart;
963 if (x == -1)
964 x = -2;
965 return x;
966 }
967 /* The fractional part is non-zero, so we don't have to worry about
968 * making this match the hash of some other type.
969 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000970 * Since the VAX D double format has 56 mantissa bits, which is the
971 * most of any double format in use, each of these parts may have as
972 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000973 * So, assuming sizeof(long) >= 4, each part can be broken into two
974 * longs; frexp and multiplication are used to do that.
975 * Also, since the Cray double format has 15 exponent bits, which is
976 * the most of any double format in use, shifting the exponent field
977 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000978 */
Tim Peters39dce292000-08-15 03:34:48 +0000979 v = frexp(v, &expo);
980 v *= 2147483648.0; /* 2**31 */
981 hipart = (long)v; /* take the top 32 bits */
982 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
983 x = hipart + (long)v + (expo << 15);
984 if (x == -1)
985 x = -2;
986 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000987}
988
989long
Fred Drake100814d2000-07-09 15:48:49 +0000990_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000991{
992#if SIZEOF_LONG >= SIZEOF_VOID_P
993 return (long)p;
994#else
995 /* convert to a Python long and hash that */
996 PyObject* longobj;
997 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000998
Fred Drake13634cf2000-06-29 19:17:04 +0000999 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1000 x = -1;
1001 goto finally;
1002 }
1003 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001004
Fred Drake13634cf2000-06-29 19:17:04 +00001005finally:
1006 Py_XDECREF(longobj);
1007 return x;
1008#endif
1009}
1010
1011
Guido van Rossum9bfef441993-03-29 10:43:31 +00001012long
Fred Drake100814d2000-07-09 15:48:49 +00001013PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001014{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001015 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001016 if (tp->tp_hash != NULL)
1017 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001018 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001019 return _Py_HashPointer(v); /* Use address as hash value */
1020 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001021 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001022 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001023 return -1;
1024}
1025
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001026PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001027PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001028{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001030
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001032 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033 w = PyString_InternFromString(name);
1034 if (w == NULL)
1035 return NULL;
1036 res = PyObject_GetAttr(v, w);
1037 Py_XDECREF(w);
1038 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001039}
1040
1041int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001042PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001043{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001044 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001045 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001046 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001047 return 1;
1048 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001049 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001050 return 0;
1051}
1052
1053int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001054PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001055{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056 PyObject *s;
1057 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001058
Tim Peters6d6c1a32001-08-02 04:15:00 +00001059 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001060 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001061 s = PyString_InternFromString(name);
1062 if (s == NULL)
1063 return -1;
1064 res = PyObject_SetAttr(v, s, w);
1065 Py_XDECREF(s);
1066 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001067}
1068
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001069PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001070PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001071{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072 PyTypeObject *tp = v->ob_type;
1073
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001074 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001075#ifdef Py_USING_UNICODE
1076 /* The Unicode to string conversion is done here because the
1077 existing tp_getattro slots expect a string object as name
1078 and we wouldn't want to break those. */
1079 if (PyUnicode_Check(name)) {
1080 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1081 if (name == NULL)
1082 return NULL;
1083 }
1084 else
1085#endif
1086 {
1087 PyErr_SetString(PyExc_TypeError,
1088 "attribute name must be string");
1089 return NULL;
1090 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001091 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 if (tp->tp_getattro != NULL)
1093 return (*tp->tp_getattro)(v, name);
1094 if (tp->tp_getattr != NULL)
1095 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1096 PyErr_Format(PyExc_AttributeError,
1097 "'%.50s' object has no attribute '%.400s'",
1098 tp->tp_name, PyString_AS_STRING(name));
1099 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001100}
1101
1102int
Fred Drake100814d2000-07-09 15:48:49 +00001103PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001104{
1105 PyObject *res = PyObject_GetAttr(v, name);
1106 if (res != NULL) {
1107 Py_DECREF(res);
1108 return 1;
1109 }
1110 PyErr_Clear();
1111 return 0;
1112}
1113
1114int
Fred Drake100814d2000-07-09 15:48:49 +00001115PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001116{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001118 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001119
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001120 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001121#ifdef Py_USING_UNICODE
1122 /* The Unicode to string conversion is done here because the
1123 existing tp_setattro slots expect a string object as name
1124 and we wouldn't want to break those. */
1125 if (PyUnicode_Check(name)) {
1126 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1127 if (name == NULL)
1128 return -1;
1129 }
Tim Peters803526b2002-07-07 05:13:56 +00001130 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001131#endif
1132 {
1133 PyErr_SetString(PyExc_TypeError,
1134 "attribute name must be string");
1135 return -1;
1136 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001137 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001138 else
1139 Py_INCREF(name);
1140
1141 PyString_InternInPlace(&name);
1142 if (tp->tp_setattro != NULL) {
1143 err = (*tp->tp_setattro)(v, name, value);
1144 Py_DECREF(name);
1145 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001146 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147 if (tp->tp_setattr != NULL) {
1148 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1149 Py_DECREF(name);
1150 return err;
1151 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001152 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1154 PyErr_Format(PyExc_TypeError,
1155 "'%.100s' object has no attributes "
1156 "(%s .%.100s)",
1157 tp->tp_name,
1158 value==NULL ? "del" : "assign to",
1159 PyString_AS_STRING(name));
1160 else
1161 PyErr_Format(PyExc_TypeError,
1162 "'%.100s' object has only read-only attributes "
1163 "(%s .%.100s)",
1164 tp->tp_name,
1165 value==NULL ? "del" : "assign to",
1166 PyString_AS_STRING(name));
1167 return -1;
1168}
1169
1170/* Helper to get a pointer to an object's __dict__ slot, if any */
1171
1172PyObject **
1173_PyObject_GetDictPtr(PyObject *obj)
1174{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001175 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 PyTypeObject *tp = obj->ob_type;
1177
1178 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1179 return NULL;
1180 dictoffset = tp->tp_dictoffset;
1181 if (dictoffset == 0)
1182 return NULL;
1183 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001184 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001185 size_t size;
1186
1187 tsize = ((PyVarObject *)obj)->ob_size;
1188 if (tsize < 0)
1189 tsize = -tsize;
1190 size = _PyObject_VAR_SIZE(tp, tsize);
1191
Tim Peters6d483d32001-10-06 21:27:34 +00001192 dictoffset += (long)size;
1193 assert(dictoffset > 0);
1194 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 }
1196 return (PyObject **) ((char *)obj + dictoffset);
1197}
1198
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001200PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001201{
1202 Py_INCREF(obj);
1203 return obj;
1204}
1205
Michael W. Hudson1593f502004-09-14 17:09:47 +00001206/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1207
Raymond Hettinger01538262003-03-17 08:24:35 +00001208PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1210{
1211 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001212 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001213 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001215 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 PyObject **dictptr;
1217
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001218 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001219#ifdef Py_USING_UNICODE
1220 /* The Unicode to string conversion is done here because the
1221 existing tp_setattro slots expect a string object as name
1222 and we wouldn't want to break those. */
1223 if (PyUnicode_Check(name)) {
1224 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1225 if (name == NULL)
1226 return NULL;
1227 }
Tim Peters803526b2002-07-07 05:13:56 +00001228 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001229#endif
1230 {
1231 PyErr_SetString(PyExc_TypeError,
1232 "attribute name must be string");
1233 return NULL;
1234 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001235 }
1236 else
1237 Py_INCREF(name);
1238
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001240 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001241 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 }
1243
Guido van Rossum056fbf42002-08-19 19:22:50 +00001244 /* Inline _PyType_Lookup */
1245 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001246 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001247 PyObject *mro, *base, *dict;
1248
1249 /* Look in tp_dict of types in MRO */
1250 mro = tp->tp_mro;
1251 assert(mro != NULL);
1252 assert(PyTuple_Check(mro));
1253 n = PyTuple_GET_SIZE(mro);
1254 for (i = 0; i < n; i++) {
1255 base = PyTuple_GET_ITEM(mro, i);
1256 if (PyClass_Check(base))
1257 dict = ((PyClassObject *)base)->cl_dict;
1258 else {
1259 assert(PyType_Check(base));
1260 dict = ((PyTypeObject *)base)->tp_dict;
1261 }
1262 assert(dict && PyDict_Check(dict));
1263 descr = PyDict_GetItem(dict, name);
1264 if (descr != NULL)
1265 break;
1266 }
1267 }
1268
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001269 Py_XINCREF(descr);
1270
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001272 if (descr != NULL &&
1273 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001275 if (f != NULL && PyDescr_IsData(descr)) {
1276 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001277 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001278 goto done;
1279 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001280 }
1281
Guido van Rossumc66ff442002-08-19 16:50:48 +00001282 /* Inline _PyObject_GetDictPtr */
1283 dictoffset = tp->tp_dictoffset;
1284 if (dictoffset != 0) {
1285 PyObject *dict;
1286 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001288 size_t size;
1289
1290 tsize = ((PyVarObject *)obj)->ob_size;
1291 if (tsize < 0)
1292 tsize = -tsize;
1293 size = _PyObject_VAR_SIZE(tp, tsize);
1294
1295 dictoffset += (long)size;
1296 assert(dictoffset > 0);
1297 assert(dictoffset % SIZEOF_VOID_P == 0);
1298 }
1299 dictptr = (PyObject **) ((char *)obj + dictoffset);
1300 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001302 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 if (res != NULL) {
1304 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001305 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001306 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 }
1308 }
1309 }
1310
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001311 if (f != NULL) {
1312 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001313 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001314 goto done;
1315 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316
1317 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001318 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001319 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001320 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 }
1322
1323 PyErr_Format(PyExc_AttributeError,
1324 "'%.50s' object has no attribute '%.400s'",
1325 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001326 done:
1327 Py_DECREF(name);
1328 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329}
1330
1331int
1332PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1333{
1334 PyTypeObject *tp = obj->ob_type;
1335 PyObject *descr;
1336 descrsetfunc f;
1337 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001338 int res = -1;
1339
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001340 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001341#ifdef Py_USING_UNICODE
1342 /* The Unicode to string conversion is done here because the
1343 existing tp_setattro slots expect a string object as name
1344 and we wouldn't want to break those. */
1345 if (PyUnicode_Check(name)) {
1346 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1347 if (name == NULL)
1348 return -1;
1349 }
Tim Peters803526b2002-07-07 05:13:56 +00001350 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001351#endif
1352 {
1353 PyErr_SetString(PyExc_TypeError,
1354 "attribute name must be string");
1355 return -1;
1356 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001357 }
1358 else
1359 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001360
1361 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001362 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001363 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 }
1365
1366 descr = _PyType_Lookup(tp, name);
1367 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001368 if (descr != NULL &&
1369 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001371 if (f != NULL && PyDescr_IsData(descr)) {
1372 res = f(descr, obj, value);
1373 goto done;
1374 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375 }
1376
1377 dictptr = _PyObject_GetDictPtr(obj);
1378 if (dictptr != NULL) {
1379 PyObject *dict = *dictptr;
1380 if (dict == NULL && value != NULL) {
1381 dict = PyDict_New();
1382 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001383 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384 *dictptr = dict;
1385 }
1386 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001387 if (value == NULL)
1388 res = PyDict_DelItem(dict, name);
1389 else
1390 res = PyDict_SetItem(dict, name, value);
1391 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1392 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001393 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 }
1395 }
1396
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001397 if (f != NULL) {
1398 res = f(descr, obj, value);
1399 goto done;
1400 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401
1402 if (descr == NULL) {
1403 PyErr_Format(PyExc_AttributeError,
1404 "'%.50s' object has no attribute '%.400s'",
1405 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001406 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 }
1408
1409 PyErr_Format(PyExc_AttributeError,
1410 "'%.50s' object attribute '%.400s' is read-only",
1411 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001412 done:
1413 Py_DECREF(name);
1414 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001415}
1416
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001417/* Test a value used as condition, e.g., in a for or if statement.
1418 Return -1 if an error occurred */
1419
1420int
Fred Drake100814d2000-07-09 15:48:49 +00001421PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001422{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001423 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001424 if (v == Py_True)
1425 return 1;
1426 if (v == Py_False)
1427 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001428 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001429 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001430 else if (v->ob_type->tp_as_number != NULL &&
1431 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001432 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001433 else if (v->ob_type->tp_as_mapping != NULL &&
1434 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001435 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001436 else if (v->ob_type->tp_as_sequence != NULL &&
1437 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001438 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1439 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001440 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001441 /* if it is negative, it should be either -1 or -2 */
1442 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001443}
1444
Tim Peters803526b2002-07-07 05:13:56 +00001445/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001446 Return -1 if an error occurred */
1447
1448int
Fred Drake100814d2000-07-09 15:48:49 +00001449PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001450{
1451 int res;
1452 res = PyObject_IsTrue(v);
1453 if (res < 0)
1454 return res;
1455 return res == 0;
1456}
1457
Guido van Rossum5524a591995-01-10 15:26:20 +00001458/* Coerce two numeric types to the "larger" one.
1459 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001460 Return value:
1461 -1 if an error occurred;
1462 0 if the coercion succeeded (and then the reference counts are increased);
1463 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001464*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001465int
Fred Drake100814d2000-07-09 15:48:49 +00001466PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001467{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001468 register PyObject *v = *pv;
1469 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001470 int res;
1471
Guido van Rossum517c7d42002-04-26 02:49:14 +00001472 /* Shortcut only for old-style types */
1473 if (v->ob_type == w->ob_type &&
1474 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1475 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001476 Py_INCREF(v);
1477 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001478 return 0;
1479 }
1480 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1481 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1482 if (res <= 0)
1483 return res;
1484 }
1485 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1486 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1487 if (res <= 0)
1488 return res;
1489 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001490 return 1;
1491}
1492
Guido van Rossume797ec12001-01-17 15:24:28 +00001493/* Coerce two numeric types to the "larger" one.
1494 Increment the reference count on each argument.
1495 Return -1 and raise an exception if no coercion is possible
1496 (and then no reference count is incremented).
1497*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001498int
Fred Drake100814d2000-07-09 15:48:49 +00001499PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001500{
1501 int err = PyNumber_CoerceEx(pv, pw);
1502 if (err <= 0)
1503 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001504 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001505 return -1;
1506}
1507
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001508
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001509/* Test whether an object can be called */
1510
1511int
Fred Drake100814d2000-07-09 15:48:49 +00001512PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001513{
1514 if (x == NULL)
1515 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001516 if (PyInstance_Check(x)) {
1517 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001518 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001519 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001520 return 0;
1521 }
1522 /* Could test recursively but don't, for fear of endless
1523 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001524 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001525 return 1;
1526 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001527 else {
1528 return x->ob_type->tp_call != NULL;
1529 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001530}
1531
Tim Peters7eea37e2001-09-04 22:08:56 +00001532/* Helper for PyObject_Dir.
1533 Merge the __dict__ of aclass into dict, and recursively also all
1534 the __dict__s of aclass's base classes. The order of merging isn't
1535 defined, as it's expected that only the final set of dict keys is
1536 interesting.
1537 Return 0 on success, -1 on error.
1538*/
1539
1540static int
1541merge_class_dict(PyObject* dict, PyObject* aclass)
1542{
1543 PyObject *classdict;
1544 PyObject *bases;
1545
1546 assert(PyDict_Check(dict));
1547 assert(aclass);
1548
1549 /* Merge in the type's dict (if any). */
1550 classdict = PyObject_GetAttrString(aclass, "__dict__");
1551 if (classdict == NULL)
1552 PyErr_Clear();
1553 else {
1554 int status = PyDict_Update(dict, classdict);
1555 Py_DECREF(classdict);
1556 if (status < 0)
1557 return -1;
1558 }
1559
1560 /* Recursively merge in the base types' (if any) dicts. */
1561 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001562 if (bases == NULL)
1563 PyErr_Clear();
1564 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001565 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001566 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001567 n = PySequence_Size(bases); /* This better be right */
1568 if (n < 0)
1569 PyErr_Clear();
1570 else {
1571 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001572 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001573 PyObject *base = PySequence_GetItem(bases, i);
1574 if (base == NULL) {
1575 Py_DECREF(bases);
1576 return -1;
1577 }
Tim Peters18e70832003-02-05 19:35:19 +00001578 status = merge_class_dict(dict, base);
1579 Py_DECREF(base);
1580 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001581 Py_DECREF(bases);
1582 return -1;
1583 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001584 }
1585 }
1586 Py_DECREF(bases);
1587 }
1588 return 0;
1589}
1590
Tim Peters305b5852001-09-17 02:38:46 +00001591/* Helper for PyObject_Dir.
1592 If obj has an attr named attrname that's a list, merge its string
1593 elements into keys of dict.
1594 Return 0 on success, -1 on error. Errors due to not finding the attr,
1595 or the attr not being a list, are suppressed.
1596*/
1597
1598static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001599merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001600{
1601 PyObject *list;
1602 int result = 0;
1603
1604 assert(PyDict_Check(dict));
1605 assert(obj);
1606 assert(attrname);
1607
1608 list = PyObject_GetAttrString(obj, attrname);
1609 if (list == NULL)
1610 PyErr_Clear();
1611
1612 else if (PyList_Check(list)) {
1613 int i;
1614 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1615 PyObject *item = PyList_GET_ITEM(list, i);
1616 if (PyString_Check(item)) {
1617 result = PyDict_SetItem(dict, item, Py_None);
1618 if (result < 0)
1619 break;
1620 }
1621 }
1622 }
1623
1624 Py_XDECREF(list);
1625 return result;
1626}
1627
Tim Peters7eea37e2001-09-04 22:08:56 +00001628/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1629 docstring, which should be kept in synch with this implementation. */
1630
1631PyObject *
1632PyObject_Dir(PyObject *arg)
1633{
1634 /* Set exactly one of these non-NULL before the end. */
1635 PyObject *result = NULL; /* result list */
1636 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1637
1638 /* If NULL arg, return the locals. */
1639 if (arg == NULL) {
1640 PyObject *locals = PyEval_GetLocals();
1641 if (locals == NULL)
1642 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001643 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001644 if (result == NULL)
1645 goto error;
1646 }
1647
1648 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001649 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001650 masterdict = PyObject_GetAttrString(arg, "__dict__");
1651 if (masterdict == NULL)
1652 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001653 if (!PyDict_Check(masterdict)) {
1654 PyErr_SetString(PyExc_TypeError,
1655 "module.__dict__ is not a dictionary");
1656 goto error;
1657 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001658 }
1659
1660 /* Elif some form of type or class, grab its dict and its bases.
1661 We deliberately don't suck up its __class__, as methods belonging
1662 to the metaclass would probably be more confusing than helpful. */
1663 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1664 masterdict = PyDict_New();
1665 if (masterdict == NULL)
1666 goto error;
1667 if (merge_class_dict(masterdict, arg) < 0)
1668 goto error;
1669 }
1670
1671 /* Else look at its dict, and the attrs reachable from its class. */
1672 else {
1673 PyObject *itsclass;
1674 /* Create a dict to start with. CAUTION: Not everything
1675 responding to __dict__ returns a dict! */
1676 masterdict = PyObject_GetAttrString(arg, "__dict__");
1677 if (masterdict == NULL) {
1678 PyErr_Clear();
1679 masterdict = PyDict_New();
1680 }
1681 else if (!PyDict_Check(masterdict)) {
1682 Py_DECREF(masterdict);
1683 masterdict = PyDict_New();
1684 }
1685 else {
1686 /* The object may have returned a reference to its
1687 dict, so copy it to avoid mutating it. */
1688 PyObject *temp = PyDict_Copy(masterdict);
1689 Py_DECREF(masterdict);
1690 masterdict = temp;
1691 }
1692 if (masterdict == NULL)
1693 goto error;
1694
Tim Peters305b5852001-09-17 02:38:46 +00001695 /* Merge in __members__ and __methods__ (if any).
1696 XXX Would like this to go away someday; for now, it's
1697 XXX needed to get at im_self etc of method objects. */
1698 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1699 goto error;
1700 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1701 goto error;
1702
Tim Peters7eea37e2001-09-04 22:08:56 +00001703 /* Merge in attrs reachable from its class.
1704 CAUTION: Not all objects have a __class__ attr. */
1705 itsclass = PyObject_GetAttrString(arg, "__class__");
1706 if (itsclass == NULL)
1707 PyErr_Clear();
1708 else {
1709 int status = merge_class_dict(masterdict, itsclass);
1710 Py_DECREF(itsclass);
1711 if (status < 0)
1712 goto error;
1713 }
1714 }
1715
1716 assert((result == NULL) ^ (masterdict == NULL));
1717 if (masterdict != NULL) {
1718 /* The result comes from its keys. */
1719 assert(result == NULL);
1720 result = PyDict_Keys(masterdict);
1721 if (result == NULL)
1722 goto error;
1723 }
1724
1725 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001726 if (!PyList_Check(result)) {
Tim Petersf4aca752004-09-23 02:39:37 +00001727 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001728 "Expected keys() to be a list.");
1729 goto error;
1730 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001731 if (PyList_Sort(result) != 0)
1732 goto error;
1733 else
1734 goto normal_return;
1735
1736 error:
1737 Py_XDECREF(result);
1738 result = NULL;
1739 /* fall through */
1740 normal_return:
1741 Py_XDECREF(masterdict);
1742 return result;
1743}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001744
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001745/*
1746NoObject is usable as a non-NULL undefined value, used by the macro None.
1747There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001748so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001749(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750*/
1751
Guido van Rossum0c182a11992-03-27 17:26:13 +00001752/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001753static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001754none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001755{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001756 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001757}
1758
Barry Warsaw9bf16442001-01-23 16:24:35 +00001759/* ARGUSED */
1760static void
Tim Peters803526b2002-07-07 05:13:56 +00001761none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001762{
1763 /* This should never get called, but we also don't want to SEGV if
1764 * we accidently decref None out of existance.
1765 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001766 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001767}
1768
1769
Guido van Rossumba21a492001-08-16 08:17:26 +00001770static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001771 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001772 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001773 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001774 0,
1775 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001776 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001777 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001778 0, /*tp_getattr*/
1779 0, /*tp_setattr*/
1780 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001781 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001782 0, /*tp_as_number*/
1783 0, /*tp_as_sequence*/
1784 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001785 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001786};
1787
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001788PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001789 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001790};
1791
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001792/* NotImplemented is an object that can be used to signal that an
1793 operation is not implemented for the given type combination. */
1794
1795static PyObject *
1796NotImplemented_repr(PyObject *op)
1797{
1798 return PyString_FromString("NotImplemented");
1799}
1800
1801static PyTypeObject PyNotImplemented_Type = {
1802 PyObject_HEAD_INIT(&PyType_Type)
1803 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001804 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001805 0,
1806 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001807 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001808 0, /*tp_print*/
1809 0, /*tp_getattr*/
1810 0, /*tp_setattr*/
1811 0, /*tp_compare*/
1812 (reprfunc)NotImplemented_repr, /*tp_repr*/
1813 0, /*tp_as_number*/
1814 0, /*tp_as_sequence*/
1815 0, /*tp_as_mapping*/
1816 0, /*tp_hash */
1817};
1818
1819PyObject _Py_NotImplementedStruct = {
1820 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1821};
1822
Guido van Rossumba21a492001-08-16 08:17:26 +00001823void
1824_Py_ReadyTypes(void)
1825{
1826 if (PyType_Ready(&PyType_Type) < 0)
1827 Py_FatalError("Can't initialize 'type'");
1828
Fred Drake0a4dd392004-07-02 18:57:45 +00001829 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1830 Py_FatalError("Can't initialize 'weakref'");
1831
Guido van Rossum77f6a652002-04-03 22:41:51 +00001832 if (PyType_Ready(&PyBool_Type) < 0)
1833 Py_FatalError("Can't initialize 'bool'");
1834
Guido van Rossumcacfc072002-05-24 19:01:59 +00001835 if (PyType_Ready(&PyString_Type) < 0)
1836 Py_FatalError("Can't initialize 'str'");
1837
Guido van Rossumba21a492001-08-16 08:17:26 +00001838 if (PyType_Ready(&PyList_Type) < 0)
1839 Py_FatalError("Can't initialize 'list'");
1840
1841 if (PyType_Ready(&PyNone_Type) < 0)
1842 Py_FatalError("Can't initialize type(None)");
1843
1844 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1845 Py_FatalError("Can't initialize type(NotImplemented)");
1846}
1847
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001848
Guido van Rossum84a90321996-05-22 16:34:47 +00001849#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001850
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001851void
Fred Drake100814d2000-07-09 15:48:49 +00001852_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853{
Tim Peters34592512002-07-11 06:23:50 +00001854 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001855 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001856 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001857 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858}
1859
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001860void
Fred Drake100814d2000-07-09 15:48:49 +00001861_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001862{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001863#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001864 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001865#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001866 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001867 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001868 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001869 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001870 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001871#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001872 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1873 if (p == op)
1874 break;
1875 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001876 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001877 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001878#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001879 op->_ob_next->_ob_prev = op->_ob_prev;
1880 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001881 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001882 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001883}
1884
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001885void
Fred Drake100814d2000-07-09 15:48:49 +00001886_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001887{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001888 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001889 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001890 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001891}
1892
Tim Peters269b2a62003-04-17 19:52:29 +00001893/* Print all live objects. Because PyObject_Print is called, the
1894 * interpreter must be in a healthy state.
1895 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001896void
Fred Drake100814d2000-07-09 15:48:49 +00001897_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001898{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001899 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001900 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001901 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001902 /* XXX(twouters) cast refcount to long until %zd is
1903 universally available */
1904 fprintf(fp, "%p [%ld] ", op, (long)op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001905 if (PyObject_Print(op, fp, 0) != 0)
1906 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001907 putc('\n', fp);
1908 }
1909}
1910
Tim Peters269b2a62003-04-17 19:52:29 +00001911/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1912 * doesn't make any calls to the Python C API, so is always safe to call.
1913 */
1914void
1915_Py_PrintReferenceAddresses(FILE *fp)
1916{
1917 PyObject *op;
1918 fprintf(fp, "Remaining object addresses:\n");
1919 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001920 /* XXX(twouters) cast refcount to long until %zd is
1921 universally available */
1922 fprintf(fp, "%p [%ld] %s\n", op, (long)op->ob_refcnt,
Tim Peters21d7d4d2003-04-18 00:45:59 +00001923 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001924}
1925
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001926PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001927_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001928{
1929 int i, n;
1930 PyObject *t = NULL;
1931 PyObject *res, *op;
1932
1933 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1934 return NULL;
1935 op = refchain._ob_next;
1936 res = PyList_New(0);
1937 if (res == NULL)
1938 return NULL;
1939 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1940 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001941 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001942 op = op->_ob_next;
1943 if (op == &refchain)
1944 return res;
1945 }
1946 if (PyList_Append(res, op) < 0) {
1947 Py_DECREF(res);
1948 return NULL;
1949 }
1950 op = op->_ob_next;
1951 }
1952 return res;
1953}
1954
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001955#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001956
1957
1958/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001959PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001960
1961
1962/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001963Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001964
1965
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001966/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001967
Thomas Wouters334fb892000-07-25 12:56:38 +00001968void *
Fred Drake100814d2000-07-09 15:48:49 +00001969PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001970{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001971 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001972}
1973
Thomas Wouters334fb892000-07-25 12:56:38 +00001974void *
1975PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001976{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001977 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001978}
1979
1980void
Thomas Wouters334fb892000-07-25 12:56:38 +00001981PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001982{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001983 PyMem_FREE(p);
1984}
1985
1986
Guido van Rossum86610361998-04-10 22:32:46 +00001987/* These methods are used to control infinite recursion in repr, str, print,
1988 etc. Container objects that may recursively contain themselves,
1989 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1990 Py_ReprLeave() to avoid infinite recursion.
1991
1992 Py_ReprEnter() returns 0 the first time it is called for a particular
1993 object and 1 every time thereafter. It returns -1 if an exception
1994 occurred. Py_ReprLeave() has no return value.
1995
1996 See dictobject.c and listobject.c for examples of use.
1997*/
1998
1999#define KEY "Py_Repr"
2000
2001int
Fred Drake100814d2000-07-09 15:48:49 +00002002Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002003{
2004 PyObject *dict;
2005 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002006 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002007
2008 dict = PyThreadState_GetDict();
2009 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00002010 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002011 list = PyDict_GetItemString(dict, KEY);
2012 if (list == NULL) {
2013 list = PyList_New(0);
2014 if (list == NULL)
2015 return -1;
2016 if (PyDict_SetItemString(dict, KEY, list) < 0)
2017 return -1;
2018 Py_DECREF(list);
2019 }
2020 i = PyList_GET_SIZE(list);
2021 while (--i >= 0) {
2022 if (PyList_GET_ITEM(list, i) == obj)
2023 return 1;
2024 }
2025 PyList_Append(list, obj);
2026 return 0;
2027}
2028
2029void
Fred Drake100814d2000-07-09 15:48:49 +00002030Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002031{
2032 PyObject *dict;
2033 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002034 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002035
2036 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002037 if (dict == NULL)
2038 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002039 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002040 if (list == NULL || !PyList_Check(list))
2041 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002042 i = PyList_GET_SIZE(list);
2043 /* Count backwards because we always expect obj to be list[-1] */
2044 while (--i >= 0) {
2045 if (PyList_GET_ITEM(list, i) == obj) {
2046 PyList_SetSlice(list, i, i + 1, NULL);
2047 break;
2048 }
2049 }
2050}
Guido van Rossumd724b232000-03-13 16:01:29 +00002051
Tim Peters803526b2002-07-07 05:13:56 +00002052/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002053
Tim Peters803526b2002-07-07 05:13:56 +00002054/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002055int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002056
Tim Peters803526b2002-07-07 05:13:56 +00002057/* List of objects that still need to be cleaned up, singly linked via their
2058 * gc headers' gc_prev pointers.
2059 */
2060PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002061
Tim Peters803526b2002-07-07 05:13:56 +00002062/* Add op to the _PyTrash_delete_later list. Called when the current
2063 * call-stack depth gets large. op must be a currently untracked gc'ed
2064 * object, with refcount 0. Py_DECREF must already have been called on it.
2065 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002066void
Fred Drake100814d2000-07-09 15:48:49 +00002067_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002068{
Tim Peters803526b2002-07-07 05:13:56 +00002069 assert(PyObject_IS_GC(op));
2070 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2071 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002072 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002073 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002074}
2075
Tim Peters803526b2002-07-07 05:13:56 +00002076/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2077 * the call-stack unwinds again.
2078 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002079void
Fred Drake100814d2000-07-09 15:48:49 +00002080_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002081{
2082 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002083 PyObject *op = _PyTrash_delete_later;
2084 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002085
Neil Schemenauerf589c052002-03-29 03:05:54 +00002086 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002087 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002088
Tim Peters803526b2002-07-07 05:13:56 +00002089 /* Call the deallocator directly. This used to try to
2090 * fool Py_DECREF into calling it indirectly, but
2091 * Py_DECREF was already called on this object, and in
2092 * assorted non-release builds calling Py_DECREF again ends
2093 * up distorting allocation statistics.
2094 */
2095 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002096 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002097 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002098 --_PyTrash_delete_nesting;
2099 }
2100}