blob: 0ce4332f763163a1c356274ad3accaa364e599fb [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;
Armin Rigoe1709372006-04-12 17:06:05 +00008
9Py_ssize_t
10_Py_GetRefTotal(void)
11{
12 PyObject *o;
13 Py_ssize_t total = _Py_RefTotal;
14 /* ignore the references to the dummy object of the dicts and sets
15 because they are not reliable and not useful (now that the
16 hash table code is well-tested) */
17 o = _PyDict_Dummy();
18 if (o != NULL)
19 total -= o->ob_refcnt;
20 o = _PySet_Dummy();
21 if (o != NULL)
22 total -= o->ob_refcnt;
23 return total;
24}
25#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000026
Mark Hammonda2905272002-07-29 13:42:14 +000027int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000028
Guido van Rossum3f5da241990-12-20 15:06:42 +000029/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
30 These are used by the individual routines for object creation.
31 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000032
Tim Peters78be7992003-03-23 02:51:01 +000033#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000034/* Head of circular doubly-linked list of all objects. These are linked
35 * together via the _ob_prev and _ob_next members of a PyObject, which
36 * exist only in a Py_TRACE_REFS build.
37 */
Tim Peters78be7992003-03-23 02:51:01 +000038static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000039
Tim Peters7571a0f2003-03-23 17:52:28 +000040/* Insert op at the front of the list of all objects. If force is true,
41 * op is added even if _ob_prev and _ob_next are non-NULL already. If
42 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
43 * force should be true if and only if op points to freshly allocated,
44 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000045 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000046 * Note that objects are normally added to the list via _Py_NewReference,
47 * which is called by PyObject_Init. Not all objects are initialized that
48 * way, though; exceptions include statically allocated type objects, and
49 * statically allocated singletons (like Py_True and Py_None).
50 */
Tim Peters36eb4df2003-03-23 03:33:13 +000051void
Tim Peters7571a0f2003-03-23 17:52:28 +000052_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000053{
Tim Peters7571a0f2003-03-23 17:52:28 +000054#ifdef Py_DEBUG
55 if (!force) {
56 /* If it's initialized memory, op must be in or out of
57 * the list unambiguously.
58 */
59 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
60 }
Tim Peters78be7992003-03-23 02:51:01 +000061#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000062 if (force || op->_ob_prev == NULL) {
63 op->_ob_next = refchain._ob_next;
64 op->_ob_prev = &refchain;
65 refchain._ob_next->_ob_prev = op;
66 refchain._ob_next = op;
67 }
68}
69#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000070
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000071#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000072static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000073extern int tuple_zero_allocs, fast_tuple_allocs;
74extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000075extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076void
Fred Drake100814d2000-07-09 15:48:49 +000077dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000078{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000080
81 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000082 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000083 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000084 tp->tp_maxalloc);
85 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
86 fast_tuple_allocs, tuple_zero_allocs);
87 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
88 quick_int_allocs, quick_neg_int_allocs);
89 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
90 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000091}
92
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000093PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000094get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000095{
96 PyTypeObject *tp;
97 PyObject *result;
98 PyObject *v;
99
100 result = PyList_New(0);
101 if (result == NULL)
102 return NULL;
103 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000104 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
105 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000106 if (v == NULL) {
107 Py_DECREF(result);
108 return NULL;
109 }
110 if (PyList_Append(result, v) < 0) {
111 Py_DECREF(v);
112 Py_DECREF(result);
113 return NULL;
114 }
115 Py_DECREF(v);
116 }
117 return result;
118}
119
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000120void
Fred Drake100814d2000-07-09 15:48:49 +0000121inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000122{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000123 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000124 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000125 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000127 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000128 /* Note that as of Python 2.2, heap-allocated type objects
129 * can go away, but this code requires that they stay alive
130 * until program exit. That's why we're careful with
131 * refcounts here. type_list gets a new reference to tp,
132 * while ownership of the reference type_list used to hold
133 * (if any) was transferred to tp->tp_next in the line above.
134 * tp is thus effectively immortal after this.
135 */
136 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000138#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000139 /* Also insert in the doubly-linked list of all objects,
140 * if not already there.
141 */
142 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000143#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000144 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000145 tp->tp_allocs++;
146 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
147 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000148}
149#endif
150
Tim Peters7c321a82002-07-09 02:57:01 +0000151#ifdef Py_REF_DEBUG
152/* Log a fatal error; doesn't return. */
153void
154_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
155{
156 char buf[300];
157
158 PyOS_snprintf(buf, sizeof(buf),
Tim Peters4d073bb2006-03-23 05:38:33 +0000159 "%s:%i object at %p has negative ref count "
160 "%" PY_FORMAT_SIZE_T "d",
Tim Peters8af92d12006-03-23 05:41:24 +0000161 fname, lineno, op, op->ob_refcnt);
Tim Peters7c321a82002-07-09 02:57:01 +0000162 Py_FatalError(buf);
163}
164
165#endif /* Py_REF_DEBUG */
166
Thomas Heller1328b522004-04-22 17:23:49 +0000167void
168Py_IncRef(PyObject *o)
169{
170 Py_XINCREF(o);
171}
172
173void
174Py_DecRef(PyObject *o)
175{
176 Py_XDECREF(o);
177}
178
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000180PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000182 if (op == NULL)
183 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000184 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187 return op;
188}
189
Guido van Rossumb18618d2000-05-03 23:44:39 +0000190PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000191PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000192{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000193 if (op == NULL)
194 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000195 /* Any changes should be reflected in PyObject_INIT_VAR */
196 op->ob_size = size;
197 op->ob_type = tp;
198 _Py_NewReference((PyObject *)op);
199 return op;
200}
201
202PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000203_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000204{
205 PyObject *op;
206 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
207 if (op == NULL)
208 return PyErr_NoMemory();
209 return PyObject_INIT(op, tp);
210}
211
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000212PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000213_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000215 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000216 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000217 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000219 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000220 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000221}
222
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000223/* for binary compatibility with 2.2 */
224#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000225void
Fred Drake100814d2000-07-09 15:48:49 +0000226_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000228 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229}
230
Neal Norwitz1a997502003-01-13 20:13:12 +0000231/* Implementation of PyObject_Print with recursion checking */
232static int
233internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234{
Guido van Rossum278ef591991-07-27 21:40:24 +0000235 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000236 if (nesting > 10) {
237 PyErr_SetString(PyExc_RuntimeError, "print recursion");
238 return -1;
239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000240 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000241 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000242#ifdef USE_STACKCHECK
243 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000244 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000245 return -1;
246 }
247#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000248 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000249 if (op == NULL) {
250 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251 }
Guido van Rossum90933611991-06-07 16:10:43 +0000252 else {
253 if (op->ob_refcnt <= 0)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000254 /* XXX(twouters) cast refcount to long until %zd is
255 universally available */
256 fprintf(fp, "<refcnt %ld at %p>",
257 (long)op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000258 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000259 PyObject *s;
260 if (flags & Py_PRINT_RAW)
261 s = PyObject_Str(op);
262 else
263 s = PyObject_Repr(op);
264 if (s == NULL)
265 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000266 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000267 ret = internal_print(s, fp, Py_PRINT_RAW,
268 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000269 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000270 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000271 }
Guido van Rossum90933611991-06-07 16:10:43 +0000272 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000273 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000274 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000275 if (ret == 0) {
276 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000278 clearerr(fp);
279 ret = -1;
280 }
281 }
282 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283}
284
Neal Norwitz1a997502003-01-13 20:13:12 +0000285int
286PyObject_Print(PyObject *op, FILE *fp, int flags)
287{
288 return internal_print(op, fp, flags, 0);
289}
290
291
Barry Warsaw9bf16442001-01-23 16:24:35 +0000292/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000293void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000294{
Barry Warsaweefb1072001-02-22 22:39:18 +0000295 if (op == NULL)
296 fprintf(stderr, "NULL\n");
297 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000298 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000299 (void)PyObject_Print(op, stderr, 0);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000300 /* XXX(twouters) cast refcount to long until %zd is
301 universally available */
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000302 fprintf(stderr, "\n"
303 "type : %s\n"
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000304 "refcount: %ld\n"
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000305 "address : %p\n",
306 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000307 (long)op->ob_refcnt,
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000308 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000309 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000310}
Barry Warsaw903138f2001-01-23 16:33:18 +0000311
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000313PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000314{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000315 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000316 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000317#ifdef USE_STACKCHECK
318 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000319 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000320 return NULL;
321 }
322#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000323 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000325 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000326 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000327 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000328 else {
329 PyObject *res;
330 res = (*v->ob_type->tp_repr)(v);
331 if (res == NULL)
332 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000333#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000334 if (PyUnicode_Check(res)) {
335 PyObject* str;
Anthony Baxter262c00a2006-03-30 10:53:17 +0000336 str = PyUnicode_AsEncodedString(res, NULL, NULL);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000337 Py_DECREF(res);
338 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000339 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000340 else
341 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000342 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000343#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000344 if (!PyString_Check(res)) {
345 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000346 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000347 res->ob_type->tp_name);
348 Py_DECREF(res);
349 return NULL;
350 }
351 return res;
352 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353}
354
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000356_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000357{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000358 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000359 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000360 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000362 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000364 return v;
365 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000366#ifdef Py_USING_UNICODE
367 if (PyUnicode_CheckExact(v)) {
368 Py_INCREF(v);
369 return v;
370 }
371#endif
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000372 if (v->ob_type->tp_str == NULL)
373 return PyObject_Repr(v);
374
375 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000376 if (res == NULL)
377 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000378 type_ok = PyString_Check(res);
379#ifdef Py_USING_UNICODE
380 type_ok = type_ok || PyUnicode_Check(res);
381#endif
382 if (!type_ok) {
383 PyErr_Format(PyExc_TypeError,
384 "__str__ returned non-string (type %.200s)",
385 res->ob_type->tp_name);
386 Py_DECREF(res);
387 return NULL;
388 }
389 return res;
390}
391
392PyObject *
393PyObject_Str(PyObject *v)
394{
395 PyObject *res = _PyObject_Str(v);
396 if (res == NULL)
397 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000398#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000399 if (PyUnicode_Check(res)) {
400 PyObject* str;
401 str = PyUnicode_AsEncodedString(res, NULL, NULL);
402 Py_DECREF(res);
403 if (str)
404 res = str;
405 else
406 return NULL;
407 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000408#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +0000409 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000410 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000411}
412
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000413#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000414PyObject *
415PyObject_Unicode(PyObject *v)
416{
417 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000418 PyObject *func;
Neal Norwitz75801462006-03-14 06:02:16 +0000419 PyObject *str;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000420 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000421
Georg Brandl3daf7582006-03-13 22:22:11 +0000422 if (v == NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000423 res = PyString_FromString("<NULL>");
Neal Norwitz75801462006-03-14 06:02:16 +0000424 if (res == NULL)
425 return NULL;
426 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
427 Py_DECREF(res);
428 return str;
Georg Brandl3daf7582006-03-13 22:22:11 +0000429 } else if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000430 Py_INCREF(v);
431 return v;
432 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000433 /* XXX As soon as we have a tp_unicode slot, we should
434 check this before trying the __unicode__
435 method. */
436 if (unicodestr == NULL) {
437 unicodestr= PyString_InternFromString("__unicode__");
438 if (unicodestr == NULL)
439 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000440 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000441 func = PyObject_GetAttr(v, unicodestr);
442 if (func != NULL) {
443 res = PyEval_CallObject(func, (PyObject *)NULL);
444 Py_DECREF(func);
445 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000446 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000447 PyErr_Clear();
448 if (PyUnicode_Check(v)) {
449 /* For a Unicode subtype that's didn't overwrite __unicode__,
450 return a true Unicode object with the same data. */
451 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
452 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000453 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000454 if (PyString_CheckExact(v)) {
455 Py_INCREF(v);
456 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000457 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000458 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000459 if (v->ob_type->tp_str != NULL)
460 res = (*v->ob_type->tp_str)(v);
461 else
462 res = PyObject_Repr(v);
463 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000464 }
465 if (res == NULL)
466 return NULL;
467 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000468 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000469 Py_DECREF(res);
Neal Norwitz75801462006-03-14 06:02:16 +0000470 res = str;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000471 }
472 return res;
473}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000474#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000475
476
Guido van Rossuma4073002002-05-31 20:03:54 +0000477/* Helper to warn about deprecated tp_compare return values. Return:
478 -2 for an exception;
479 -1 if v < w;
480 0 if v == w;
481 1 if v > w.
482 (This function cannot return 2.)
483*/
484static int
485adjust_tp_compare(int c)
486{
487 if (PyErr_Occurred()) {
488 if (c != -1 && c != -2) {
489 PyObject *t, *v, *tb;
490 PyErr_Fetch(&t, &v, &tb);
491 if (PyErr_Warn(PyExc_RuntimeWarning,
492 "tp_compare didn't return -1 or -2 "
493 "for exception") < 0) {
494 Py_XDECREF(t);
495 Py_XDECREF(v);
496 Py_XDECREF(tb);
497 }
498 else
499 PyErr_Restore(t, v, tb);
500 }
501 return -2;
502 }
503 else if (c < -1 || c > 1) {
504 if (PyErr_Warn(PyExc_RuntimeWarning,
505 "tp_compare didn't return -1, 0 or 1") < 0)
506 return -2;
507 else
508 return c < -1 ? -1 : 1;
509 }
510 else {
511 assert(c >= -1 && c <= 1);
512 return c;
513 }
514}
515
516
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000517/* Macro to get the tp_richcompare field of a type if defined */
518#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
519 ? (t)->tp_richcompare : NULL)
520
Guido van Rossume797ec12001-01-17 15:24:28 +0000521/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000522int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000523
Guido van Rossume797ec12001-01-17 15:24:28 +0000524/* Try a genuine rich comparison, returning an object. Return:
525 NULL for exception;
526 NotImplemented if this particular rich comparison is not implemented or
527 undefined;
528 some object not equal to NotImplemented if it is implemented
529 (this latter object may not be a Boolean).
530*/
531static PyObject *
532try_rich_compare(PyObject *v, PyObject *w, int op)
533{
534 richcmpfunc f;
535 PyObject *res;
536
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000537 if (v->ob_type != w->ob_type &&
538 PyType_IsSubtype(w->ob_type, v->ob_type) &&
539 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000540 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000541 if (res != Py_NotImplemented)
542 return res;
543 Py_DECREF(res);
544 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000545 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000546 res = (*f)(v, w, op);
547 if (res != Py_NotImplemented)
548 return res;
549 Py_DECREF(res);
550 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000551 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000552 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000553 }
554 res = Py_NotImplemented;
555 Py_INCREF(res);
556 return res;
557}
558
559/* Try a genuine rich comparison, returning an int. Return:
560 -1 for exception (including the case where try_rich_compare() returns an
561 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000562 0 if the outcome is false;
563 1 if the outcome is true;
564 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000565*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000566static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000567try_rich_compare_bool(PyObject *v, PyObject *w, int op)
568{
569 PyObject *res;
570 int ok;
571
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000572 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000573 return 2; /* Shortcut, avoid INCREF+DECREF */
574 res = try_rich_compare(v, w, op);
575 if (res == NULL)
576 return -1;
577 if (res == Py_NotImplemented) {
578 Py_DECREF(res);
579 return 2;
580 }
581 ok = PyObject_IsTrue(res);
582 Py_DECREF(res);
583 return ok;
584}
585
586/* Try rich comparisons to determine a 3-way comparison. Return:
587 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000588 -1 if v < w;
589 0 if v == w;
590 1 if v > w;
591 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000592*/
593static int
594try_rich_to_3way_compare(PyObject *v, PyObject *w)
595{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000596 static struct { int op; int outcome; } tries[3] = {
597 /* Try this operator, and if it is true, use this outcome: */
598 {Py_EQ, 0},
599 {Py_LT, -1},
600 {Py_GT, 1},
601 };
602 int i;
603
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000604 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000605 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000606
607 for (i = 0; i < 3; i++) {
608 switch (try_rich_compare_bool(v, w, tries[i].op)) {
609 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000610 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000611 case 1:
612 return tries[i].outcome;
613 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000614 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000615
616 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000617}
618
619/* Try a 3-way comparison, returning an int. Return:
620 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000621 -1 if v < w;
622 0 if v == w;
623 1 if v > w;
624 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000625*/
626static int
627try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000628{
629 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000630 cmpfunc f;
631
632 /* Comparisons involving instances are given to instance_compare,
633 which has the same return conventions as this function. */
634
Guido van Rossumab3b0342001-09-18 20:38:53 +0000635 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000636 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000637 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000638 if (PyInstance_Check(w))
639 return (*w->ob_type->tp_compare)(v, w);
640
Guido van Rossumab3b0342001-09-18 20:38:53 +0000641 /* If both have the same (non-NULL) tp_compare, use it. */
642 if (f != NULL && f == w->ob_type->tp_compare) {
643 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000644 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000645 }
646
647 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
648 if (f == _PyObject_SlotCompare ||
649 w->ob_type->tp_compare == _PyObject_SlotCompare)
650 return _PyObject_SlotCompare(v, w);
651
Armin Rigoa1748132004-12-23 22:13:13 +0000652 /* If we're here, v and w,
653 a) are not instances;
654 b) have different types or a type without tp_compare; and
655 c) don't have a user-defined tp_compare.
656 tp_compare implementations in C assume that both arguments
657 have their type, so we give up if the coercion fails or if
658 it yields types which are still incompatible (which can
659 happen with a user-defined nb_coerce).
660 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000661 c = PyNumber_CoerceEx(&v, &w);
662 if (c < 0)
663 return -2;
664 if (c > 0)
665 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000666 f = v->ob_type->tp_compare;
667 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000668 c = (*f)(v, w);
669 Py_DECREF(v);
670 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000671 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000672 }
673
Guido van Rossume797ec12001-01-17 15:24:28 +0000674 /* No comparison defined */
675 Py_DECREF(v);
676 Py_DECREF(w);
677 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000678}
679
Guido van Rossume797ec12001-01-17 15:24:28 +0000680/* Final fallback 3-way comparison, returning an int. Return:
681 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000682 -1 if v < w;
683 0 if v == w;
684 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000685*/
686static int
687default_3way_compare(PyObject *v, PyObject *w)
688{
689 int c;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000690 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000691
692 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000693 /* When comparing these pointers, they must be cast to
694 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
695 * uintptr_t). ANSI specifies that pointer compares other
696 * than == and != to non-related structures are undefined.
697 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000698 Py_uintptr_t vv = (Py_uintptr_t)v;
699 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000700 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
701 }
702
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000703#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000704 /* Special case for Unicode */
705 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
706 c = PyUnicode_Compare(v, w);
707 if (!PyErr_Occurred())
708 return c;
709 /* TypeErrors are ignored: if Unicode coercion fails due
710 to one of the arguments not having the right type, we
711 continue as defined by the coercion protocol (see
712 above). Luckily, decoding errors are reported as
713 ValueErrors and are not masked by this technique. */
714 if (!PyErr_ExceptionMatches(PyExc_TypeError))
715 return -2;
716 PyErr_Clear();
717 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000718#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000719
Guido van Rossum0871e932001-01-22 19:28:09 +0000720 /* None is smaller than anything */
721 if (v == Py_None)
722 return -1;
723 if (w == Py_None)
724 return 1;
725
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000726 /* different type: compare type names; numbers are smaller */
727 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000728 vname = "";
729 else
730 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000731 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000732 wname = "";
733 else
734 wname = w->ob_type->tp_name;
735 c = strcmp(vname, wname);
736 if (c < 0)
737 return -1;
738 if (c > 0)
739 return 1;
740 /* Same type name, or (more likely) incomparable numeric types */
741 return ((Py_uintptr_t)(v->ob_type) < (
742 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000743}
744
Tim Peters6d60b2e2001-05-07 20:53:51 +0000745/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000746 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000747 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000748 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000749 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000750 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000751 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000752*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000753static int
Fred Drake100814d2000-07-09 15:48:49 +0000754do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000755{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000756 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000757 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000758
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000759 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000760 && (f = v->ob_type->tp_compare) != NULL) {
761 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000762 if (PyInstance_Check(v)) {
763 /* Instance tp_compare has a different signature.
764 But if it returns undefined we fall through. */
765 if (c != 2)
766 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000767 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000768 }
769 else
770 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000771 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000772 /* We only get here if one of the following is true:
773 a) v and w have different types
774 b) v and w have the same type, which doesn't have tp_compare
775 c) v and w are instances, and either __cmp__ is not defined or
776 __cmp__ returns NotImplemented
777 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000778 c = try_rich_to_3way_compare(v, w);
779 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000780 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000781 c = try_3way_compare(v, w);
782 if (c < 2)
783 return c;
784 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000785}
786
Tim Petersc99213f2001-11-04 05:57:16 +0000787/* Compare v to w. Return
788 -1 if v < w or exception (PyErr_Occurred() true in latter case).
789 0 if v == w.
790 1 if v > w.
791 XXX The docs (C API manual) say the return value is undefined in case
792 XXX of error.
793*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000794int
Fred Drake100814d2000-07-09 15:48:49 +0000795PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000796{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000797 int result;
798
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000799 if (v == NULL || w == NULL) {
800 PyErr_BadInternalCall();
801 return -1;
802 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000803 if (v == w)
804 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000805 if (Py_EnterRecursiveCall(" in cmp"))
806 return -1;
807 result = do_cmp(v, w);
808 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000809 return result < 0 ? -1 : result;
810}
811
Tim Petersc99213f2001-11-04 05:57:16 +0000812/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000813static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000814convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000815{
Guido van Rossume797ec12001-01-17 15:24:28 +0000816 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000817 switch (op) {
818 case Py_LT: c = c < 0; break;
819 case Py_LE: c = c <= 0; break;
820 case Py_EQ: c = c == 0; break;
821 case Py_NE: c = c != 0; break;
822 case Py_GT: c = c > 0; break;
823 case Py_GE: c = c >= 0; break;
824 }
825 result = c ? Py_True : Py_False;
826 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000827 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000828}
Tim Peters803526b2002-07-07 05:13:56 +0000829
Tim Petersc99213f2001-11-04 05:57:16 +0000830/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
831 Return
832 NULL if error
833 Py_True if v op w
834 Py_False if not (v op w)
835*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000836static PyObject *
837try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
838{
839 int c;
840
841 c = try_3way_compare(v, w);
842 if (c >= 2)
843 c = default_3way_compare(v, w);
844 if (c <= -2)
845 return NULL;
846 return convert_3way_to_object(op, c);
847}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000848
Tim Petersc99213f2001-11-04 05:57:16 +0000849/* Do rich comparison on v and w. Return
850 NULL if error
851 Else a new reference to an object other than Py_NotImplemented, usually(?):
852 Py_True if v op w
853 Py_False if not (v op w)
854*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000855static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000856do_richcmp(PyObject *v, PyObject *w, int op)
857{
858 PyObject *res;
859
860 res = try_rich_compare(v, w, op);
861 if (res != Py_NotImplemented)
862 return res;
863 Py_DECREF(res);
864
865 return try_3way_to_rich_compare(v, w, op);
866}
867
Tim Petersc99213f2001-11-04 05:57:16 +0000868/* Return:
869 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000870 some object not equal to NotImplemented if it is implemented
871 (this latter object may not be a Boolean).
872*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000873PyObject *
874PyObject_RichCompare(PyObject *v, PyObject *w, int op)
875{
876 PyObject *res;
877
878 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000879 if (Py_EnterRecursiveCall(" in cmp"))
880 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000881
Armin Rigo2b3eb402003-10-28 12:05:48 +0000882 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000883 get out cheap (don't bother with coercions etc.). */
884 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
885 cmpfunc fcmp;
886 richcmpfunc frich = RICHCOMPARE(v->ob_type);
887 /* If the type has richcmp, try it first. try_rich_compare
888 tries it two-sided, which is not needed since we've a
889 single type only. */
890 if (frich != NULL) {
891 res = (*frich)(v, w, op);
892 if (res != Py_NotImplemented)
893 goto Done;
894 Py_DECREF(res);
895 }
896 /* No richcmp, or this particular richmp not implemented.
897 Try 3-way cmp. */
898 fcmp = v->ob_type->tp_compare;
899 if (fcmp != NULL) {
900 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000901 c = adjust_tp_compare(c);
902 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000903 res = NULL;
904 goto Done;
905 }
906 res = convert_3way_to_object(op, c);
907 goto Done;
908 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000909 }
Tim Peters67754e92001-11-04 07:29:31 +0000910
911 /* Fast path not taken, or couldn't deliver a useful result. */
912 res = do_richcmp(v, w, op);
913Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000914 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000915 return res;
916}
917
Tim Petersde9725f2001-05-05 10:06:17 +0000918/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000919int
920PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
921{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000922 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000923 int ok;
924
Raymond Hettinger93d44812004-03-21 17:01:44 +0000925 /* Quick result when objects are the same.
926 Guarantees that identity implies equality. */
927 if (v == w) {
928 if (op == Py_EQ)
929 return 1;
930 else if (op == Py_NE)
931 return 0;
932 }
933
934 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000935 if (res == NULL)
936 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000937 if (PyBool_Check(res))
938 ok = (res == Py_True);
939 else
940 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000941 Py_DECREF(res);
942 return ok;
943}
Fred Drake13634cf2000-06-29 19:17:04 +0000944
945/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000946 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000947
948 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
949*/
950
951long
Fred Drake100814d2000-07-09 15:48:49 +0000952_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000953{
Tim Peters39dce292000-08-15 03:34:48 +0000954 double intpart, fractpart;
955 int expo;
956 long hipart;
957 long x; /* the final hash value */
958 /* This is designed so that Python numbers of different types
959 * that compare equal hash to the same value; otherwise comparisons
960 * of mapping keys will turn out weird.
961 */
962
Tim Peters39dce292000-08-15 03:34:48 +0000963 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000964 if (fractpart == 0.0) {
965 /* This must return the same hash as an equal int or long. */
966 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
967 /* Convert to long and use its hash. */
968 PyObject *plong; /* converted to Python long */
969 if (Py_IS_INFINITY(intpart))
970 /* can't convert to long int -- arbitrary */
971 v = v < 0 ? -271828.0 : 314159.0;
972 plong = PyLong_FromDouble(v);
973 if (plong == NULL)
974 return -1;
975 x = PyObject_Hash(plong);
976 Py_DECREF(plong);
977 return x;
978 }
979 /* Fits in a C long == a Python int, so is its own hash. */
980 x = (long)intpart;
981 if (x == -1)
982 x = -2;
983 return x;
984 }
985 /* The fractional part is non-zero, so we don't have to worry about
986 * making this match the hash of some other type.
987 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000988 * Since the VAX D double format has 56 mantissa bits, which is the
989 * most of any double format in use, each of these parts may have as
990 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000991 * So, assuming sizeof(long) >= 4, each part can be broken into two
992 * longs; frexp and multiplication are used to do that.
993 * Also, since the Cray double format has 15 exponent bits, which is
994 * the most of any double format in use, shifting the exponent field
995 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000996 */
Tim Peters39dce292000-08-15 03:34:48 +0000997 v = frexp(v, &expo);
998 v *= 2147483648.0; /* 2**31 */
999 hipart = (long)v; /* take the top 32 bits */
1000 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1001 x = hipart + (long)v + (expo << 15);
1002 if (x == -1)
1003 x = -2;
1004 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001005}
1006
1007long
Fred Drake100814d2000-07-09 15:48:49 +00001008_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001009{
1010#if SIZEOF_LONG >= SIZEOF_VOID_P
1011 return (long)p;
1012#else
1013 /* convert to a Python long and hash that */
1014 PyObject* longobj;
1015 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001016
Fred Drake13634cf2000-06-29 19:17:04 +00001017 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1018 x = -1;
1019 goto finally;
1020 }
1021 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001022
Fred Drake13634cf2000-06-29 19:17:04 +00001023finally:
1024 Py_XDECREF(longobj);
1025 return x;
1026#endif
1027}
1028
1029
Guido van Rossum9bfef441993-03-29 10:43:31 +00001030long
Fred Drake100814d2000-07-09 15:48:49 +00001031PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001032{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001033 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001034 if (tp->tp_hash != NULL)
1035 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001036 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001037 return _Py_HashPointer(v); /* Use address as hash value */
1038 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001039 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001040 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001041 return -1;
1042}
1043
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001044PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001045PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001046{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001048
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001050 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051 w = PyString_InternFromString(name);
1052 if (w == NULL)
1053 return NULL;
1054 res = PyObject_GetAttr(v, w);
1055 Py_XDECREF(w);
1056 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001057}
1058
1059int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001060PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001062 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001063 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001064 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001065 return 1;
1066 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001067 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001068 return 0;
1069}
1070
1071int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001072PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001073{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074 PyObject *s;
1075 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001076
Tim Peters6d6c1a32001-08-02 04:15:00 +00001077 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001078 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079 s = PyString_InternFromString(name);
1080 if (s == NULL)
1081 return -1;
1082 res = PyObject_SetAttr(v, s, w);
1083 Py_XDECREF(s);
1084 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001085}
1086
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001087PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001088PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001089{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090 PyTypeObject *tp = v->ob_type;
1091
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001092 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001093#ifdef Py_USING_UNICODE
1094 /* The Unicode to string conversion is done here because the
1095 existing tp_getattro slots expect a string object as name
1096 and we wouldn't want to break those. */
1097 if (PyUnicode_Check(name)) {
1098 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1099 if (name == NULL)
1100 return NULL;
1101 }
1102 else
1103#endif
1104 {
1105 PyErr_SetString(PyExc_TypeError,
1106 "attribute name must be string");
1107 return NULL;
1108 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001109 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001110 if (tp->tp_getattro != NULL)
1111 return (*tp->tp_getattro)(v, name);
1112 if (tp->tp_getattr != NULL)
1113 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1114 PyErr_Format(PyExc_AttributeError,
1115 "'%.50s' object has no attribute '%.400s'",
1116 tp->tp_name, PyString_AS_STRING(name));
1117 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001118}
1119
1120int
Fred Drake100814d2000-07-09 15:48:49 +00001121PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001122{
1123 PyObject *res = PyObject_GetAttr(v, name);
1124 if (res != NULL) {
1125 Py_DECREF(res);
1126 return 1;
1127 }
1128 PyErr_Clear();
1129 return 0;
1130}
1131
1132int
Fred Drake100814d2000-07-09 15:48:49 +00001133PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001134{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001136 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001137
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001138 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001139#ifdef Py_USING_UNICODE
1140 /* The Unicode to string conversion is done here because the
1141 existing tp_setattro slots expect a string object as name
1142 and we wouldn't want to break those. */
1143 if (PyUnicode_Check(name)) {
1144 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1145 if (name == NULL)
1146 return -1;
1147 }
Tim Peters803526b2002-07-07 05:13:56 +00001148 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001149#endif
1150 {
1151 PyErr_SetString(PyExc_TypeError,
1152 "attribute name must be string");
1153 return -1;
1154 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001155 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001156 else
1157 Py_INCREF(name);
1158
1159 PyString_InternInPlace(&name);
1160 if (tp->tp_setattro != NULL) {
1161 err = (*tp->tp_setattro)(v, name, value);
1162 Py_DECREF(name);
1163 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001164 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 if (tp->tp_setattr != NULL) {
1166 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1167 Py_DECREF(name);
1168 return err;
1169 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001170 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001171 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1172 PyErr_Format(PyExc_TypeError,
1173 "'%.100s' object has no attributes "
1174 "(%s .%.100s)",
1175 tp->tp_name,
1176 value==NULL ? "del" : "assign to",
1177 PyString_AS_STRING(name));
1178 else
1179 PyErr_Format(PyExc_TypeError,
1180 "'%.100s' object has only read-only attributes "
1181 "(%s .%.100s)",
1182 tp->tp_name,
1183 value==NULL ? "del" : "assign to",
1184 PyString_AS_STRING(name));
1185 return -1;
1186}
1187
1188/* Helper to get a pointer to an object's __dict__ slot, if any */
1189
1190PyObject **
1191_PyObject_GetDictPtr(PyObject *obj)
1192{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001193 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 PyTypeObject *tp = obj->ob_type;
1195
1196 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1197 return NULL;
1198 dictoffset = tp->tp_dictoffset;
1199 if (dictoffset == 0)
1200 return NULL;
1201 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001202 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001203 size_t size;
1204
1205 tsize = ((PyVarObject *)obj)->ob_size;
1206 if (tsize < 0)
1207 tsize = -tsize;
1208 size = _PyObject_VAR_SIZE(tp, tsize);
1209
Tim Peters6d483d32001-10-06 21:27:34 +00001210 dictoffset += (long)size;
1211 assert(dictoffset > 0);
1212 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 }
1214 return (PyObject **) ((char *)obj + dictoffset);
1215}
1216
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001218PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001219{
1220 Py_INCREF(obj);
1221 return obj;
1222}
1223
Michael W. Hudson1593f502004-09-14 17:09:47 +00001224/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1225
Raymond Hettinger01538262003-03-17 08:24:35 +00001226PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001227PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1228{
1229 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001230 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001231 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001233 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 PyObject **dictptr;
1235
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001236 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001237#ifdef Py_USING_UNICODE
1238 /* The Unicode to string conversion is done here because the
1239 existing tp_setattro slots expect a string object as name
1240 and we wouldn't want to break those. */
1241 if (PyUnicode_Check(name)) {
1242 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1243 if (name == NULL)
1244 return NULL;
1245 }
Tim Peters803526b2002-07-07 05:13:56 +00001246 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001247#endif
1248 {
1249 PyErr_SetString(PyExc_TypeError,
1250 "attribute name must be string");
1251 return NULL;
1252 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001253 }
1254 else
1255 Py_INCREF(name);
1256
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001258 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001259 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260 }
1261
Guido van Rossum056fbf42002-08-19 19:22:50 +00001262 /* Inline _PyType_Lookup */
1263 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001264 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001265 PyObject *mro, *base, *dict;
1266
1267 /* Look in tp_dict of types in MRO */
1268 mro = tp->tp_mro;
1269 assert(mro != NULL);
1270 assert(PyTuple_Check(mro));
1271 n = PyTuple_GET_SIZE(mro);
1272 for (i = 0; i < n; i++) {
1273 base = PyTuple_GET_ITEM(mro, i);
1274 if (PyClass_Check(base))
1275 dict = ((PyClassObject *)base)->cl_dict;
1276 else {
1277 assert(PyType_Check(base));
1278 dict = ((PyTypeObject *)base)->tp_dict;
1279 }
1280 assert(dict && PyDict_Check(dict));
1281 descr = PyDict_GetItem(dict, name);
1282 if (descr != NULL)
1283 break;
1284 }
1285 }
1286
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001287 Py_XINCREF(descr);
1288
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001290 if (descr != NULL &&
1291 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001293 if (f != NULL && PyDescr_IsData(descr)) {
1294 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001295 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001296 goto done;
1297 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298 }
1299
Guido van Rossumc66ff442002-08-19 16:50:48 +00001300 /* Inline _PyObject_GetDictPtr */
1301 dictoffset = tp->tp_dictoffset;
1302 if (dictoffset != 0) {
1303 PyObject *dict;
1304 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001305 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001306 size_t size;
1307
1308 tsize = ((PyVarObject *)obj)->ob_size;
1309 if (tsize < 0)
1310 tsize = -tsize;
1311 size = _PyObject_VAR_SIZE(tp, tsize);
1312
1313 dictoffset += (long)size;
1314 assert(dictoffset > 0);
1315 assert(dictoffset % SIZEOF_VOID_P == 0);
1316 }
1317 dictptr = (PyObject **) ((char *)obj + dictoffset);
1318 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001320 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 if (res != NULL) {
1322 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001323 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001324 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 }
1326 }
1327 }
1328
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001329 if (f != NULL) {
1330 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001331 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001332 goto done;
1333 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334
1335 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001336 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001337 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001338 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 }
1340
1341 PyErr_Format(PyExc_AttributeError,
1342 "'%.50s' object has no attribute '%.400s'",
1343 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001344 done:
1345 Py_DECREF(name);
1346 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347}
1348
1349int
1350PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1351{
1352 PyTypeObject *tp = obj->ob_type;
1353 PyObject *descr;
1354 descrsetfunc f;
1355 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001356 int res = -1;
1357
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001358 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001359#ifdef Py_USING_UNICODE
1360 /* The Unicode to string conversion is done here because the
1361 existing tp_setattro slots expect a string object as name
1362 and we wouldn't want to break those. */
1363 if (PyUnicode_Check(name)) {
1364 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1365 if (name == NULL)
1366 return -1;
1367 }
Tim Peters803526b2002-07-07 05:13:56 +00001368 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001369#endif
1370 {
1371 PyErr_SetString(PyExc_TypeError,
1372 "attribute name must be string");
1373 return -1;
1374 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001375 }
1376 else
1377 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378
1379 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001380 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001381 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001382 }
1383
1384 descr = _PyType_Lookup(tp, name);
1385 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001386 if (descr != NULL &&
1387 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001389 if (f != NULL && PyDescr_IsData(descr)) {
1390 res = f(descr, obj, value);
1391 goto done;
1392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393 }
1394
1395 dictptr = _PyObject_GetDictPtr(obj);
1396 if (dictptr != NULL) {
1397 PyObject *dict = *dictptr;
1398 if (dict == NULL && value != NULL) {
1399 dict = PyDict_New();
1400 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001401 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 *dictptr = dict;
1403 }
1404 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 if (value == NULL)
1406 res = PyDict_DelItem(dict, name);
1407 else
1408 res = PyDict_SetItem(dict, name, value);
1409 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1410 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001411 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001412 }
1413 }
1414
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001415 if (f != NULL) {
1416 res = f(descr, obj, value);
1417 goto done;
1418 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419
1420 if (descr == NULL) {
1421 PyErr_Format(PyExc_AttributeError,
1422 "'%.50s' object has no attribute '%.400s'",
1423 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001424 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001425 }
1426
1427 PyErr_Format(PyExc_AttributeError,
1428 "'%.50s' object attribute '%.400s' is read-only",
1429 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001430 done:
1431 Py_DECREF(name);
1432 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001433}
1434
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001435/* Test a value used as condition, e.g., in a for or if statement.
1436 Return -1 if an error occurred */
1437
1438int
Fred Drake100814d2000-07-09 15:48:49 +00001439PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001440{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001441 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001442 if (v == Py_True)
1443 return 1;
1444 if (v == Py_False)
1445 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001446 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001447 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001448 else if (v->ob_type->tp_as_number != NULL &&
1449 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001450 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001451 else if (v->ob_type->tp_as_mapping != NULL &&
1452 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001453 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001454 else if (v->ob_type->tp_as_sequence != NULL &&
1455 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001456 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1457 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001458 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001459 /* if it is negative, it should be either -1 or -2 */
1460 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001461}
1462
Tim Peters803526b2002-07-07 05:13:56 +00001463/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001464 Return -1 if an error occurred */
1465
1466int
Fred Drake100814d2000-07-09 15:48:49 +00001467PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001468{
1469 int res;
1470 res = PyObject_IsTrue(v);
1471 if (res < 0)
1472 return res;
1473 return res == 0;
1474}
1475
Guido van Rossum5524a591995-01-10 15:26:20 +00001476/* Coerce two numeric types to the "larger" one.
1477 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001478 Return value:
1479 -1 if an error occurred;
1480 0 if the coercion succeeded (and then the reference counts are increased);
1481 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001482*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001483int
Fred Drake100814d2000-07-09 15:48:49 +00001484PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001485{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001486 register PyObject *v = *pv;
1487 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001488 int res;
1489
Guido van Rossum517c7d42002-04-26 02:49:14 +00001490 /* Shortcut only for old-style types */
1491 if (v->ob_type == w->ob_type &&
1492 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1493 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001494 Py_INCREF(v);
1495 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001496 return 0;
1497 }
1498 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1499 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1500 if (res <= 0)
1501 return res;
1502 }
1503 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1504 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1505 if (res <= 0)
1506 return res;
1507 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001508 return 1;
1509}
1510
Guido van Rossume797ec12001-01-17 15:24:28 +00001511/* Coerce two numeric types to the "larger" one.
1512 Increment the reference count on each argument.
1513 Return -1 and raise an exception if no coercion is possible
1514 (and then no reference count is incremented).
1515*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001516int
Fred Drake100814d2000-07-09 15:48:49 +00001517PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001518{
1519 int err = PyNumber_CoerceEx(pv, pw);
1520 if (err <= 0)
1521 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001522 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001523 return -1;
1524}
1525
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001526
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001527/* Test whether an object can be called */
1528
1529int
Fred Drake100814d2000-07-09 15:48:49 +00001530PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001531{
1532 if (x == NULL)
1533 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001534 if (PyInstance_Check(x)) {
1535 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001536 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001537 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001538 return 0;
1539 }
1540 /* Could test recursively but don't, for fear of endless
1541 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001542 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001543 return 1;
1544 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545 else {
1546 return x->ob_type->tp_call != NULL;
1547 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001548}
1549
Tim Peters7eea37e2001-09-04 22:08:56 +00001550/* Helper for PyObject_Dir.
1551 Merge the __dict__ of aclass into dict, and recursively also all
1552 the __dict__s of aclass's base classes. The order of merging isn't
1553 defined, as it's expected that only the final set of dict keys is
1554 interesting.
1555 Return 0 on success, -1 on error.
1556*/
1557
1558static int
1559merge_class_dict(PyObject* dict, PyObject* aclass)
1560{
1561 PyObject *classdict;
1562 PyObject *bases;
1563
1564 assert(PyDict_Check(dict));
1565 assert(aclass);
1566
1567 /* Merge in the type's dict (if any). */
1568 classdict = PyObject_GetAttrString(aclass, "__dict__");
1569 if (classdict == NULL)
1570 PyErr_Clear();
1571 else {
1572 int status = PyDict_Update(dict, classdict);
1573 Py_DECREF(classdict);
1574 if (status < 0)
1575 return -1;
1576 }
1577
1578 /* Recursively merge in the base types' (if any) dicts. */
1579 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001580 if (bases == NULL)
1581 PyErr_Clear();
1582 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001583 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001584 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001585 n = PySequence_Size(bases); /* This better be right */
1586 if (n < 0)
1587 PyErr_Clear();
1588 else {
1589 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001590 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001591 PyObject *base = PySequence_GetItem(bases, i);
1592 if (base == NULL) {
1593 Py_DECREF(bases);
1594 return -1;
1595 }
Tim Peters18e70832003-02-05 19:35:19 +00001596 status = merge_class_dict(dict, base);
1597 Py_DECREF(base);
1598 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001599 Py_DECREF(bases);
1600 return -1;
1601 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001602 }
1603 }
1604 Py_DECREF(bases);
1605 }
1606 return 0;
1607}
1608
Tim Peters305b5852001-09-17 02:38:46 +00001609/* Helper for PyObject_Dir.
1610 If obj has an attr named attrname that's a list, merge its string
1611 elements into keys of dict.
1612 Return 0 on success, -1 on error. Errors due to not finding the attr,
1613 or the attr not being a list, are suppressed.
1614*/
1615
1616static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001617merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001618{
1619 PyObject *list;
1620 int result = 0;
1621
1622 assert(PyDict_Check(dict));
1623 assert(obj);
1624 assert(attrname);
1625
1626 list = PyObject_GetAttrString(obj, attrname);
1627 if (list == NULL)
1628 PyErr_Clear();
1629
1630 else if (PyList_Check(list)) {
1631 int i;
1632 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1633 PyObject *item = PyList_GET_ITEM(list, i);
1634 if (PyString_Check(item)) {
1635 result = PyDict_SetItem(dict, item, Py_None);
1636 if (result < 0)
1637 break;
1638 }
1639 }
1640 }
1641
1642 Py_XDECREF(list);
1643 return result;
1644}
1645
Tim Peters7eea37e2001-09-04 22:08:56 +00001646/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1647 docstring, which should be kept in synch with this implementation. */
1648
1649PyObject *
1650PyObject_Dir(PyObject *arg)
1651{
1652 /* Set exactly one of these non-NULL before the end. */
1653 PyObject *result = NULL; /* result list */
1654 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1655
1656 /* If NULL arg, return the locals. */
1657 if (arg == NULL) {
1658 PyObject *locals = PyEval_GetLocals();
1659 if (locals == NULL)
1660 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001661 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001662 if (result == NULL)
1663 goto error;
1664 }
1665
1666 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001667 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001668 masterdict = PyObject_GetAttrString(arg, "__dict__");
1669 if (masterdict == NULL)
1670 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001671 if (!PyDict_Check(masterdict)) {
1672 PyErr_SetString(PyExc_TypeError,
1673 "module.__dict__ is not a dictionary");
1674 goto error;
1675 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001676 }
1677
1678 /* Elif some form of type or class, grab its dict and its bases.
1679 We deliberately don't suck up its __class__, as methods belonging
1680 to the metaclass would probably be more confusing than helpful. */
1681 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1682 masterdict = PyDict_New();
1683 if (masterdict == NULL)
1684 goto error;
1685 if (merge_class_dict(masterdict, arg) < 0)
1686 goto error;
1687 }
1688
1689 /* Else look at its dict, and the attrs reachable from its class. */
1690 else {
1691 PyObject *itsclass;
1692 /* Create a dict to start with. CAUTION: Not everything
1693 responding to __dict__ returns a dict! */
1694 masterdict = PyObject_GetAttrString(arg, "__dict__");
1695 if (masterdict == NULL) {
1696 PyErr_Clear();
1697 masterdict = PyDict_New();
1698 }
1699 else if (!PyDict_Check(masterdict)) {
1700 Py_DECREF(masterdict);
1701 masterdict = PyDict_New();
1702 }
1703 else {
1704 /* The object may have returned a reference to its
1705 dict, so copy it to avoid mutating it. */
1706 PyObject *temp = PyDict_Copy(masterdict);
1707 Py_DECREF(masterdict);
1708 masterdict = temp;
1709 }
1710 if (masterdict == NULL)
1711 goto error;
1712
Tim Peters305b5852001-09-17 02:38:46 +00001713 /* Merge in __members__ and __methods__ (if any).
1714 XXX Would like this to go away someday; for now, it's
1715 XXX needed to get at im_self etc of method objects. */
1716 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1717 goto error;
1718 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1719 goto error;
1720
Tim Peters7eea37e2001-09-04 22:08:56 +00001721 /* Merge in attrs reachable from its class.
1722 CAUTION: Not all objects have a __class__ attr. */
1723 itsclass = PyObject_GetAttrString(arg, "__class__");
1724 if (itsclass == NULL)
1725 PyErr_Clear();
1726 else {
1727 int status = merge_class_dict(masterdict, itsclass);
1728 Py_DECREF(itsclass);
1729 if (status < 0)
1730 goto error;
1731 }
1732 }
1733
1734 assert((result == NULL) ^ (masterdict == NULL));
1735 if (masterdict != NULL) {
1736 /* The result comes from its keys. */
1737 assert(result == NULL);
1738 result = PyDict_Keys(masterdict);
1739 if (result == NULL)
1740 goto error;
1741 }
1742
1743 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001744 if (!PyList_Check(result)) {
Tim Petersf4aca752004-09-23 02:39:37 +00001745 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001746 "Expected keys() to be a list.");
1747 goto error;
1748 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001749 if (PyList_Sort(result) != 0)
1750 goto error;
1751 else
1752 goto normal_return;
1753
1754 error:
1755 Py_XDECREF(result);
1756 result = NULL;
1757 /* fall through */
1758 normal_return:
1759 Py_XDECREF(masterdict);
1760 return result;
1761}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001762
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001763/*
1764NoObject is usable as a non-NULL undefined value, used by the macro None.
1765There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001766so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001767(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001768*/
1769
Guido van Rossum0c182a11992-03-27 17:26:13 +00001770/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001771static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001772none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001773{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001774 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001775}
1776
Barry Warsaw9bf16442001-01-23 16:24:35 +00001777/* ARGUSED */
1778static void
Tim Peters803526b2002-07-07 05:13:56 +00001779none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001780{
1781 /* This should never get called, but we also don't want to SEGV if
1782 * we accidently decref None out of existance.
1783 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001784 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001785}
1786
1787
Guido van Rossumba21a492001-08-16 08:17:26 +00001788static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001789 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001790 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001791 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001792 0,
1793 0,
Georg Brandl347b3002006-03-30 11:57:00 +00001794 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001795 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001796 0, /*tp_getattr*/
1797 0, /*tp_setattr*/
1798 0, /*tp_compare*/
Georg Brandl347b3002006-03-30 11:57:00 +00001799 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001800 0, /*tp_as_number*/
1801 0, /*tp_as_sequence*/
1802 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001803 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001804};
1805
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001806PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001807 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001808};
1809
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001810/* NotImplemented is an object that can be used to signal that an
1811 operation is not implemented for the given type combination. */
1812
1813static PyObject *
1814NotImplemented_repr(PyObject *op)
1815{
1816 return PyString_FromString("NotImplemented");
1817}
1818
1819static PyTypeObject PyNotImplemented_Type = {
1820 PyObject_HEAD_INIT(&PyType_Type)
1821 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001822 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001823 0,
1824 0,
Georg Brandl347b3002006-03-30 11:57:00 +00001825 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001826 0, /*tp_print*/
1827 0, /*tp_getattr*/
1828 0, /*tp_setattr*/
1829 0, /*tp_compare*/
Georg Brandl347b3002006-03-30 11:57:00 +00001830 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001831 0, /*tp_as_number*/
1832 0, /*tp_as_sequence*/
1833 0, /*tp_as_mapping*/
1834 0, /*tp_hash */
1835};
1836
1837PyObject _Py_NotImplementedStruct = {
1838 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1839};
1840
Guido van Rossumba21a492001-08-16 08:17:26 +00001841void
1842_Py_ReadyTypes(void)
1843{
1844 if (PyType_Ready(&PyType_Type) < 0)
1845 Py_FatalError("Can't initialize 'type'");
1846
Fred Drake0a4dd392004-07-02 18:57:45 +00001847 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1848 Py_FatalError("Can't initialize 'weakref'");
1849
Guido van Rossum77f6a652002-04-03 22:41:51 +00001850 if (PyType_Ready(&PyBool_Type) < 0)
1851 Py_FatalError("Can't initialize 'bool'");
1852
Guido van Rossumcacfc072002-05-24 19:01:59 +00001853 if (PyType_Ready(&PyString_Type) < 0)
1854 Py_FatalError("Can't initialize 'str'");
1855
Guido van Rossumba21a492001-08-16 08:17:26 +00001856 if (PyType_Ready(&PyList_Type) < 0)
1857 Py_FatalError("Can't initialize 'list'");
1858
1859 if (PyType_Ready(&PyNone_Type) < 0)
1860 Py_FatalError("Can't initialize type(None)");
1861
1862 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1863 Py_FatalError("Can't initialize type(NotImplemented)");
1864}
1865
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001866
Guido van Rossum84a90321996-05-22 16:34:47 +00001867#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001868
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001869void
Fred Drake100814d2000-07-09 15:48:49 +00001870_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001871{
Tim Peters34592512002-07-11 06:23:50 +00001872 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001873 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001874 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001875 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001876}
1877
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001878void
Fred Drake100814d2000-07-09 15:48:49 +00001879_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001881#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001882 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001883#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001884 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001885 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001886 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001887 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001888 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001889#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001890 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1891 if (p == op)
1892 break;
1893 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001894 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001895 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001896#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001897 op->_ob_next->_ob_prev = op->_ob_prev;
1898 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001899 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001900 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001901}
1902
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001903void
Fred Drake100814d2000-07-09 15:48:49 +00001904_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001905{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001906 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001907 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001908 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001909}
1910
Tim Peters269b2a62003-04-17 19:52:29 +00001911/* Print all live objects. Because PyObject_Print is called, the
1912 * interpreter must be in a healthy state.
1913 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001914void
Fred Drake100814d2000-07-09 15:48:49 +00001915_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001916{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001917 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001918 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001919 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peterscbd6f182006-04-11 19:12:33 +00001920 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001921 if (PyObject_Print(op, fp, 0) != 0)
1922 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001923 putc('\n', fp);
1924 }
1925}
1926
Tim Peters269b2a62003-04-17 19:52:29 +00001927/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1928 * doesn't make any calls to the Python C API, so is always safe to call.
1929 */
1930void
1931_Py_PrintReferenceAddresses(FILE *fp)
1932{
1933 PyObject *op;
1934 fprintf(fp, "Remaining object addresses:\n");
1935 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peterscbd6f182006-04-11 19:12:33 +00001936 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1937 op->ob_refcnt, op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001938}
1939
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001940PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001941_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001942{
1943 int i, n;
1944 PyObject *t = NULL;
1945 PyObject *res, *op;
1946
1947 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1948 return NULL;
1949 op = refchain._ob_next;
1950 res = PyList_New(0);
1951 if (res == NULL)
1952 return NULL;
1953 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1954 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001955 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001956 op = op->_ob_next;
1957 if (op == &refchain)
1958 return res;
1959 }
1960 if (PyList_Append(res, op) < 0) {
1961 Py_DECREF(res);
1962 return NULL;
1963 }
1964 op = op->_ob_next;
1965 }
1966 return res;
1967}
1968
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001969#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001970
1971
1972/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001973PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001974
1975
1976/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001977Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001978
1979
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001980/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001981
Thomas Wouters334fb892000-07-25 12:56:38 +00001982void *
Fred Drake100814d2000-07-09 15:48:49 +00001983PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001984{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001985 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001986}
1987
Thomas Wouters334fb892000-07-25 12:56:38 +00001988void *
1989PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001990{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001991 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001992}
1993
1994void
Thomas Wouters334fb892000-07-25 12:56:38 +00001995PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001996{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001997 PyMem_FREE(p);
1998}
1999
2000
Guido van Rossum86610361998-04-10 22:32:46 +00002001/* These methods are used to control infinite recursion in repr, str, print,
2002 etc. Container objects that may recursively contain themselves,
2003 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2004 Py_ReprLeave() to avoid infinite recursion.
2005
2006 Py_ReprEnter() returns 0 the first time it is called for a particular
2007 object and 1 every time thereafter. It returns -1 if an exception
2008 occurred. Py_ReprLeave() has no return value.
2009
2010 See dictobject.c and listobject.c for examples of use.
2011*/
2012
2013#define KEY "Py_Repr"
2014
2015int
Fred Drake100814d2000-07-09 15:48:49 +00002016Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002017{
2018 PyObject *dict;
2019 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002020 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002021
2022 dict = PyThreadState_GetDict();
2023 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00002024 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002025 list = PyDict_GetItemString(dict, KEY);
2026 if (list == NULL) {
2027 list = PyList_New(0);
2028 if (list == NULL)
2029 return -1;
2030 if (PyDict_SetItemString(dict, KEY, list) < 0)
2031 return -1;
2032 Py_DECREF(list);
2033 }
2034 i = PyList_GET_SIZE(list);
2035 while (--i >= 0) {
2036 if (PyList_GET_ITEM(list, i) == obj)
2037 return 1;
2038 }
2039 PyList_Append(list, obj);
2040 return 0;
2041}
2042
2043void
Fred Drake100814d2000-07-09 15:48:49 +00002044Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002045{
2046 PyObject *dict;
2047 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002048 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002049
2050 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002051 if (dict == NULL)
2052 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002053 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002054 if (list == NULL || !PyList_Check(list))
2055 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002056 i = PyList_GET_SIZE(list);
2057 /* Count backwards because we always expect obj to be list[-1] */
2058 while (--i >= 0) {
2059 if (PyList_GET_ITEM(list, i) == obj) {
2060 PyList_SetSlice(list, i, i + 1, NULL);
2061 break;
2062 }
2063 }
2064}
Guido van Rossumd724b232000-03-13 16:01:29 +00002065
Tim Peters803526b2002-07-07 05:13:56 +00002066/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002067
Tim Peters803526b2002-07-07 05:13:56 +00002068/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002069int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002070
Tim Peters803526b2002-07-07 05:13:56 +00002071/* List of objects that still need to be cleaned up, singly linked via their
2072 * gc headers' gc_prev pointers.
2073 */
2074PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002075
Tim Peters803526b2002-07-07 05:13:56 +00002076/* Add op to the _PyTrash_delete_later list. Called when the current
2077 * call-stack depth gets large. op must be a currently untracked gc'ed
2078 * object, with refcount 0. Py_DECREF must already have been called on it.
2079 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002080void
Fred Drake100814d2000-07-09 15:48:49 +00002081_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002082{
Tim Peters803526b2002-07-07 05:13:56 +00002083 assert(PyObject_IS_GC(op));
2084 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2085 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002086 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002087 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002088}
2089
Tim Peters803526b2002-07-07 05:13:56 +00002090/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2091 * the call-stack unwinds again.
2092 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002093void
Fred Drake100814d2000-07-09 15:48:49 +00002094_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002095{
2096 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002097 PyObject *op = _PyTrash_delete_later;
2098 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002099
Neil Schemenauerf589c052002-03-29 03:05:54 +00002100 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002101 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002102
Tim Peters803526b2002-07-07 05:13:56 +00002103 /* Call the deallocator directly. This used to try to
2104 * fool Py_DECREF into calling it indirectly, but
2105 * Py_DECREF was already called on this object, and in
2106 * assorted non-release builds calling Py_DECREF again ends
2107 * up distorting allocation statistics.
2108 */
2109 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002110 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002111 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002112 --_PyTrash_delete_nesting;
2113 }
2114}