blob: d3dda1b028e836eecbd381550fd25bd46420613c [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
Anthony Baxterac6bd462006-04-13 02:06:09 +00006#ifdef __cplusplus
7extern "C" {
8#endif
9
Tim Peters34592512002-07-11 06:23:50 +000010#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000011Py_ssize_t _Py_RefTotal;
Armin Rigoe1709372006-04-12 17:06:05 +000012
13Py_ssize_t
14_Py_GetRefTotal(void)
15{
16 PyObject *o;
17 Py_ssize_t total = _Py_RefTotal;
18 /* ignore the references to the dummy object of the dicts and sets
19 because they are not reliable and not useful (now that the
20 hash table code is well-tested) */
21 o = _PyDict_Dummy();
22 if (o != NULL)
23 total -= o->ob_refcnt;
24 o = _PySet_Dummy();
25 if (o != NULL)
26 total -= o->ob_refcnt;
27 return total;
28}
29#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000030
Mark Hammonda2905272002-07-29 13:42:14 +000031int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000032
Guido van Rossum3f5da241990-12-20 15:06:42 +000033/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
34 These are used by the individual routines for object creation.
35 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000036
Tim Peters78be7992003-03-23 02:51:01 +000037#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000038/* Head of circular doubly-linked list of all objects. These are linked
39 * together via the _ob_prev and _ob_next members of a PyObject, which
40 * exist only in a Py_TRACE_REFS build.
41 */
Tim Peters78be7992003-03-23 02:51:01 +000042static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000043
Tim Peters7571a0f2003-03-23 17:52:28 +000044/* Insert op at the front of the list of all objects. If force is true,
45 * op is added even if _ob_prev and _ob_next are non-NULL already. If
46 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
47 * force should be true if and only if op points to freshly allocated,
48 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000049 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000050 * Note that objects are normally added to the list via _Py_NewReference,
51 * which is called by PyObject_Init. Not all objects are initialized that
52 * way, though; exceptions include statically allocated type objects, and
53 * statically allocated singletons (like Py_True and Py_None).
54 */
Tim Peters36eb4df2003-03-23 03:33:13 +000055void
Tim Peters7571a0f2003-03-23 17:52:28 +000056_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000057{
Tim Peters7571a0f2003-03-23 17:52:28 +000058#ifdef Py_DEBUG
59 if (!force) {
60 /* If it's initialized memory, op must be in or out of
61 * the list unambiguously.
62 */
63 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
64 }
Tim Peters78be7992003-03-23 02:51:01 +000065#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000066 if (force || op->_ob_prev == NULL) {
67 op->_ob_next = refchain._ob_next;
68 op->_ob_prev = &refchain;
69 refchain._ob_next->_ob_prev = op;
70 refchain._ob_next = op;
71 }
72}
73#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000074
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000075#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000077extern int tuple_zero_allocs, fast_tuple_allocs;
78extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000079extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000080void
Fred Drake100814d2000-07-09 15:48:49 +000081dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000082{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000083 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000084
85 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000086 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000088 tp->tp_maxalloc);
89 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
90 fast_tuple_allocs, tuple_zero_allocs);
91 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
92 quick_int_allocs, quick_neg_int_allocs);
93 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
94 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000095}
96
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000097PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000098get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000099{
100 PyTypeObject *tp;
101 PyObject *result;
102 PyObject *v;
103
104 result = PyList_New(0);
105 if (result == NULL)
106 return NULL;
107 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000108 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
109 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000110 if (v == NULL) {
111 Py_DECREF(result);
112 return NULL;
113 }
114 if (PyList_Append(result, v) < 0) {
115 Py_DECREF(v);
116 Py_DECREF(result);
117 return NULL;
118 }
119 Py_DECREF(v);
120 }
121 return result;
122}
123
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000124void
Fred Drake100814d2000-07-09 15:48:49 +0000125inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000126{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000127 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000128 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000129 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000131 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000132 /* Note that as of Python 2.2, heap-allocated type objects
133 * can go away, but this code requires that they stay alive
134 * until program exit. That's why we're careful with
135 * refcounts here. type_list gets a new reference to tp,
136 * while ownership of the reference type_list used to hold
137 * (if any) was transferred to tp->tp_next in the line above.
138 * tp is thus effectively immortal after this.
139 */
140 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000141 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000142#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000143 /* Also insert in the doubly-linked list of all objects,
144 * if not already there.
145 */
146 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000147#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000148 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000149 tp->tp_allocs++;
150 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
151 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000152}
153#endif
154
Tim Peters7c321a82002-07-09 02:57:01 +0000155#ifdef Py_REF_DEBUG
156/* Log a fatal error; doesn't return. */
157void
158_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
159{
160 char buf[300];
161
162 PyOS_snprintf(buf, sizeof(buf),
Tim Peters4d073bb2006-03-23 05:38:33 +0000163 "%s:%i object at %p has negative ref count "
164 "%" PY_FORMAT_SIZE_T "d",
Tim Peters8af92d12006-03-23 05:41:24 +0000165 fname, lineno, op, op->ob_refcnt);
Tim Peters7c321a82002-07-09 02:57:01 +0000166 Py_FatalError(buf);
167}
168
169#endif /* Py_REF_DEBUG */
170
Thomas Heller1328b522004-04-22 17:23:49 +0000171void
172Py_IncRef(PyObject *o)
173{
174 Py_XINCREF(o);
175}
176
177void
178Py_DecRef(PyObject *o)
179{
180 Py_XDECREF(o);
181}
182
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000184PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000186 if (op == NULL)
187 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000188 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000191 return op;
192}
193
Guido van Rossumb18618d2000-05-03 23:44:39 +0000194PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000195PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000196{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000197 if (op == NULL)
198 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000199 /* Any changes should be reflected in PyObject_INIT_VAR */
200 op->ob_size = size;
201 op->ob_type = tp;
202 _Py_NewReference((PyObject *)op);
203 return op;
204}
205
206PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000207_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000208{
209 PyObject *op;
210 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
211 if (op == NULL)
212 return PyErr_NoMemory();
213 return PyObject_INIT(op, tp);
214}
215
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000216PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000217_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000219 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000220 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000221 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000223 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000224 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000225}
226
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000227/* for binary compatibility with 2.2 */
228#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000229void
Fred Drake100814d2000-07-09 15:48:49 +0000230_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000231{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000232 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233}
234
Neal Norwitz1a997502003-01-13 20:13:12 +0000235/* Implementation of PyObject_Print with recursion checking */
236static int
237internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238{
Guido van Rossum278ef591991-07-27 21:40:24 +0000239 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000240 if (nesting > 10) {
241 PyErr_SetString(PyExc_RuntimeError, "print recursion");
242 return -1;
243 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000245 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000246#ifdef USE_STACKCHECK
247 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000248 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000249 return -1;
250 }
251#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000252 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000253 if (op == NULL) {
254 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255 }
Guido van Rossum90933611991-06-07 16:10:43 +0000256 else {
257 if (op->ob_refcnt <= 0)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000258 /* XXX(twouters) cast refcount to long until %zd is
259 universally available */
260 fprintf(fp, "<refcnt %ld at %p>",
261 (long)op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000262 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000263 PyObject *s;
264 if (flags & Py_PRINT_RAW)
265 s = PyObject_Str(op);
266 else
267 s = PyObject_Repr(op);
268 if (s == NULL)
269 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000270 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000271 ret = internal_print(s, fp, Py_PRINT_RAW,
272 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000273 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000274 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000275 }
Guido van Rossum90933611991-06-07 16:10:43 +0000276 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000277 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000278 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000279 if (ret == 0) {
280 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000282 clearerr(fp);
283 ret = -1;
284 }
285 }
286 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287}
288
Neal Norwitz1a997502003-01-13 20:13:12 +0000289int
290PyObject_Print(PyObject *op, FILE *fp, int flags)
291{
292 return internal_print(op, fp, flags, 0);
293}
294
295
Barry Warsaw9bf16442001-01-23 16:24:35 +0000296/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000297void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000298{
Barry Warsaweefb1072001-02-22 22:39:18 +0000299 if (op == NULL)
300 fprintf(stderr, "NULL\n");
301 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000302 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000303 (void)PyObject_Print(op, stderr, 0);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000304 /* XXX(twouters) cast refcount to long until %zd is
305 universally available */
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000306 fprintf(stderr, "\n"
307 "type : %s\n"
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000308 "refcount: %ld\n"
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000309 "address : %p\n",
310 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000311 (long)op->ob_refcnt,
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000312 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000313 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000314}
Barry Warsaw903138f2001-01-23 16:33:18 +0000315
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000316PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000317PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000319 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000320 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000321#ifdef USE_STACKCHECK
322 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000323 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000324 return NULL;
325 }
326#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000327 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000329 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000330 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000331 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000332 else {
333 PyObject *res;
334 res = (*v->ob_type->tp_repr)(v);
335 if (res == NULL)
336 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000337#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000338 if (PyUnicode_Check(res)) {
339 PyObject* str;
Anthony Baxter262c00a2006-03-30 10:53:17 +0000340 str = PyUnicode_AsEncodedString(res, NULL, NULL);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000341 Py_DECREF(res);
342 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000343 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000344 else
345 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000346 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000347#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000348 if (!PyString_Check(res)) {
349 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000350 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000351 res->ob_type->tp_name);
352 Py_DECREF(res);
353 return NULL;
354 }
355 return res;
356 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357}
358
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000359PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000360_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000361{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000362 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000363 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000364 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000366 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000368 return v;
369 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000370#ifdef Py_USING_UNICODE
371 if (PyUnicode_CheckExact(v)) {
372 Py_INCREF(v);
373 return v;
374 }
375#endif
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000376 if (v->ob_type->tp_str == NULL)
377 return PyObject_Repr(v);
378
379 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000380 if (res == NULL)
381 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000382 type_ok = PyString_Check(res);
383#ifdef Py_USING_UNICODE
384 type_ok = type_ok || PyUnicode_Check(res);
385#endif
386 if (!type_ok) {
387 PyErr_Format(PyExc_TypeError,
388 "__str__ returned non-string (type %.200s)",
389 res->ob_type->tp_name);
390 Py_DECREF(res);
391 return NULL;
392 }
393 return res;
394}
395
396PyObject *
397PyObject_Str(PyObject *v)
398{
399 PyObject *res = _PyObject_Str(v);
400 if (res == NULL)
401 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000402#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000403 if (PyUnicode_Check(res)) {
404 PyObject* str;
405 str = PyUnicode_AsEncodedString(res, NULL, NULL);
406 Py_DECREF(res);
407 if (str)
408 res = str;
409 else
410 return NULL;
411 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000412#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +0000413 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000414 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000415}
416
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000417#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000418PyObject *
419PyObject_Unicode(PyObject *v)
420{
421 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000422 PyObject *func;
Neal Norwitz75801462006-03-14 06:02:16 +0000423 PyObject *str;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000424 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000425
Georg Brandl3daf7582006-03-13 22:22:11 +0000426 if (v == NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000427 res = PyString_FromString("<NULL>");
Neal Norwitz75801462006-03-14 06:02:16 +0000428 if (res == NULL)
429 return NULL;
430 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
431 Py_DECREF(res);
432 return str;
Georg Brandl3daf7582006-03-13 22:22:11 +0000433 } else if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000434 Py_INCREF(v);
435 return v;
436 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000437 /* XXX As soon as we have a tp_unicode slot, we should
438 check this before trying the __unicode__
439 method. */
440 if (unicodestr == NULL) {
441 unicodestr= PyString_InternFromString("__unicode__");
442 if (unicodestr == NULL)
443 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000444 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000445 func = PyObject_GetAttr(v, unicodestr);
446 if (func != NULL) {
447 res = PyEval_CallObject(func, (PyObject *)NULL);
448 Py_DECREF(func);
449 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000450 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000451 PyErr_Clear();
452 if (PyUnicode_Check(v)) {
453 /* For a Unicode subtype that's didn't overwrite __unicode__,
454 return a true Unicode object with the same data. */
455 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
456 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000457 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000458 if (PyString_CheckExact(v)) {
459 Py_INCREF(v);
460 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000461 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000462 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000463 if (v->ob_type->tp_str != NULL)
464 res = (*v->ob_type->tp_str)(v);
465 else
466 res = PyObject_Repr(v);
467 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000468 }
469 if (res == NULL)
470 return NULL;
471 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000472 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000473 Py_DECREF(res);
Neal Norwitz75801462006-03-14 06:02:16 +0000474 res = str;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000475 }
476 return res;
477}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000478#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000479
480
Guido van Rossuma4073002002-05-31 20:03:54 +0000481/* Helper to warn about deprecated tp_compare return values. Return:
482 -2 for an exception;
483 -1 if v < w;
484 0 if v == w;
485 1 if v > w.
486 (This function cannot return 2.)
487*/
488static int
489adjust_tp_compare(int c)
490{
491 if (PyErr_Occurred()) {
492 if (c != -1 && c != -2) {
493 PyObject *t, *v, *tb;
494 PyErr_Fetch(&t, &v, &tb);
495 if (PyErr_Warn(PyExc_RuntimeWarning,
496 "tp_compare didn't return -1 or -2 "
497 "for exception") < 0) {
498 Py_XDECREF(t);
499 Py_XDECREF(v);
500 Py_XDECREF(tb);
501 }
502 else
503 PyErr_Restore(t, v, tb);
504 }
505 return -2;
506 }
507 else if (c < -1 || c > 1) {
508 if (PyErr_Warn(PyExc_RuntimeWarning,
509 "tp_compare didn't return -1, 0 or 1") < 0)
510 return -2;
511 else
512 return c < -1 ? -1 : 1;
513 }
514 else {
515 assert(c >= -1 && c <= 1);
516 return c;
517 }
518}
519
520
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000521/* Macro to get the tp_richcompare field of a type if defined */
522#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
523 ? (t)->tp_richcompare : NULL)
524
Guido van Rossume797ec12001-01-17 15:24:28 +0000525/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000526int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000527
Guido van Rossume797ec12001-01-17 15:24:28 +0000528/* Try a genuine rich comparison, returning an object. Return:
529 NULL for exception;
530 NotImplemented if this particular rich comparison is not implemented or
531 undefined;
532 some object not equal to NotImplemented if it is implemented
533 (this latter object may not be a Boolean).
534*/
535static PyObject *
536try_rich_compare(PyObject *v, PyObject *w, int op)
537{
538 richcmpfunc f;
539 PyObject *res;
540
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000541 if (v->ob_type != w->ob_type &&
542 PyType_IsSubtype(w->ob_type, v->ob_type) &&
543 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000544 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000545 if (res != Py_NotImplemented)
546 return res;
547 Py_DECREF(res);
548 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000549 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000550 res = (*f)(v, w, op);
551 if (res != Py_NotImplemented)
552 return res;
553 Py_DECREF(res);
554 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000555 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000556 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000557 }
558 res = Py_NotImplemented;
559 Py_INCREF(res);
560 return res;
561}
562
563/* Try a genuine rich comparison, returning an int. Return:
564 -1 for exception (including the case where try_rich_compare() returns an
565 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000566 0 if the outcome is false;
567 1 if the outcome is true;
568 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000569*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000570static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000571try_rich_compare_bool(PyObject *v, PyObject *w, int op)
572{
573 PyObject *res;
574 int ok;
575
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000576 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000577 return 2; /* Shortcut, avoid INCREF+DECREF */
578 res = try_rich_compare(v, w, op);
579 if (res == NULL)
580 return -1;
581 if (res == Py_NotImplemented) {
582 Py_DECREF(res);
583 return 2;
584 }
585 ok = PyObject_IsTrue(res);
586 Py_DECREF(res);
587 return ok;
588}
589
590/* Try rich comparisons to determine a 3-way comparison. Return:
591 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000592 -1 if v < w;
593 0 if v == w;
594 1 if v > w;
595 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000596*/
597static int
598try_rich_to_3way_compare(PyObject *v, PyObject *w)
599{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000600 static struct { int op; int outcome; } tries[3] = {
601 /* Try this operator, and if it is true, use this outcome: */
602 {Py_EQ, 0},
603 {Py_LT, -1},
604 {Py_GT, 1},
605 };
606 int i;
607
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000608 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000609 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000610
611 for (i = 0; i < 3; i++) {
612 switch (try_rich_compare_bool(v, w, tries[i].op)) {
613 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000614 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000615 case 1:
616 return tries[i].outcome;
617 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000618 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000619
620 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000621}
622
623/* Try a 3-way comparison, returning an int. Return:
624 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000625 -1 if v < w;
626 0 if v == w;
627 1 if v > w;
628 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000629*/
630static int
631try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000632{
633 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000634 cmpfunc f;
635
636 /* Comparisons involving instances are given to instance_compare,
637 which has the same return conventions as this function. */
638
Guido van Rossumab3b0342001-09-18 20:38:53 +0000639 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000640 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000641 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000642 if (PyInstance_Check(w))
643 return (*w->ob_type->tp_compare)(v, w);
644
Guido van Rossumab3b0342001-09-18 20:38:53 +0000645 /* If both have the same (non-NULL) tp_compare, use it. */
646 if (f != NULL && f == w->ob_type->tp_compare) {
647 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000648 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000649 }
650
651 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
652 if (f == _PyObject_SlotCompare ||
653 w->ob_type->tp_compare == _PyObject_SlotCompare)
654 return _PyObject_SlotCompare(v, w);
655
Armin Rigoa1748132004-12-23 22:13:13 +0000656 /* If we're here, v and w,
657 a) are not instances;
658 b) have different types or a type without tp_compare; and
659 c) don't have a user-defined tp_compare.
660 tp_compare implementations in C assume that both arguments
661 have their type, so we give up if the coercion fails or if
662 it yields types which are still incompatible (which can
663 happen with a user-defined nb_coerce).
664 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000665 c = PyNumber_CoerceEx(&v, &w);
666 if (c < 0)
667 return -2;
668 if (c > 0)
669 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000670 f = v->ob_type->tp_compare;
671 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000672 c = (*f)(v, w);
673 Py_DECREF(v);
674 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000675 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000676 }
677
Guido van Rossume797ec12001-01-17 15:24:28 +0000678 /* No comparison defined */
679 Py_DECREF(v);
680 Py_DECREF(w);
681 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000682}
683
Guido van Rossume797ec12001-01-17 15:24:28 +0000684/* Final fallback 3-way comparison, returning an int. Return:
685 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000686 -1 if v < w;
687 0 if v == w;
688 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000689*/
690static int
691default_3way_compare(PyObject *v, PyObject *w)
692{
693 int c;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000694 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000695
696 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000697 /* When comparing these pointers, they must be cast to
698 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
699 * uintptr_t). ANSI specifies that pointer compares other
700 * than == and != to non-related structures are undefined.
701 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000702 Py_uintptr_t vv = (Py_uintptr_t)v;
703 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000704 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
705 }
706
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000707#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000708 /* Special case for Unicode */
709 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
710 c = PyUnicode_Compare(v, w);
711 if (!PyErr_Occurred())
712 return c;
713 /* TypeErrors are ignored: if Unicode coercion fails due
714 to one of the arguments not having the right type, we
715 continue as defined by the coercion protocol (see
716 above). Luckily, decoding errors are reported as
717 ValueErrors and are not masked by this technique. */
718 if (!PyErr_ExceptionMatches(PyExc_TypeError))
719 return -2;
720 PyErr_Clear();
721 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000722#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000723
Guido van Rossum0871e932001-01-22 19:28:09 +0000724 /* None is smaller than anything */
725 if (v == Py_None)
726 return -1;
727 if (w == Py_None)
728 return 1;
729
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000730 /* different type: compare type names; numbers are smaller */
731 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000732 vname = "";
733 else
734 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000735 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000736 wname = "";
737 else
738 wname = w->ob_type->tp_name;
739 c = strcmp(vname, wname);
740 if (c < 0)
741 return -1;
742 if (c > 0)
743 return 1;
744 /* Same type name, or (more likely) incomparable numeric types */
745 return ((Py_uintptr_t)(v->ob_type) < (
746 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000747}
748
Tim Peters6d60b2e2001-05-07 20:53:51 +0000749/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000750 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000751 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000752 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000753 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000754 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000755 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000756*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000757static int
Fred Drake100814d2000-07-09 15:48:49 +0000758do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000759{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000760 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000761 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000762
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000763 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000764 && (f = v->ob_type->tp_compare) != NULL) {
765 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000766 if (PyInstance_Check(v)) {
767 /* Instance tp_compare has a different signature.
768 But if it returns undefined we fall through. */
769 if (c != 2)
770 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000771 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000772 }
773 else
774 return adjust_tp_compare(c);
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000775 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000776 /* We only get here if one of the following is true:
777 a) v and w have different types
778 b) v and w have the same type, which doesn't have tp_compare
779 c) v and w are instances, and either __cmp__ is not defined or
780 __cmp__ returns NotImplemented
781 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000782 c = try_rich_to_3way_compare(v, w);
783 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000784 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000785 c = try_3way_compare(v, w);
786 if (c < 2)
787 return c;
788 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000789}
790
Tim Petersc99213f2001-11-04 05:57:16 +0000791/* Compare v to w. Return
792 -1 if v < w or exception (PyErr_Occurred() true in latter case).
793 0 if v == w.
794 1 if v > w.
795 XXX The docs (C API manual) say the return value is undefined in case
796 XXX of error.
797*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000798int
Fred Drake100814d2000-07-09 15:48:49 +0000799PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000800{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000801 int result;
802
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000803 if (v == NULL || w == NULL) {
804 PyErr_BadInternalCall();
805 return -1;
806 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807 if (v == w)
808 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000809 if (Py_EnterRecursiveCall(" in cmp"))
810 return -1;
811 result = do_cmp(v, w);
812 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000813 return result < 0 ? -1 : result;
814}
815
Tim Petersc99213f2001-11-04 05:57:16 +0000816/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000817static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000818convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000819{
Guido van Rossume797ec12001-01-17 15:24:28 +0000820 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000821 switch (op) {
822 case Py_LT: c = c < 0; break;
823 case Py_LE: c = c <= 0; break;
824 case Py_EQ: c = c == 0; break;
825 case Py_NE: c = c != 0; break;
826 case Py_GT: c = c > 0; break;
827 case Py_GE: c = c >= 0; break;
828 }
829 result = c ? Py_True : Py_False;
830 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000831 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000832}
Tim Peters803526b2002-07-07 05:13:56 +0000833
Tim Petersc99213f2001-11-04 05:57:16 +0000834/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
835 Return
836 NULL if error
837 Py_True if v op w
838 Py_False if not (v op w)
839*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000840static PyObject *
841try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
842{
843 int c;
844
845 c = try_3way_compare(v, w);
846 if (c >= 2)
847 c = default_3way_compare(v, w);
848 if (c <= -2)
849 return NULL;
850 return convert_3way_to_object(op, c);
851}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000852
Tim Petersc99213f2001-11-04 05:57:16 +0000853/* Do rich comparison on v and w. Return
854 NULL if error
855 Else a new reference to an object other than Py_NotImplemented, usually(?):
856 Py_True if v op w
857 Py_False if not (v op w)
858*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000859static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000860do_richcmp(PyObject *v, PyObject *w, int op)
861{
862 PyObject *res;
863
864 res = try_rich_compare(v, w, op);
865 if (res != Py_NotImplemented)
866 return res;
867 Py_DECREF(res);
868
869 return try_3way_to_rich_compare(v, w, op);
870}
871
Tim Petersc99213f2001-11-04 05:57:16 +0000872/* Return:
873 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000874 some object not equal to NotImplemented if it is implemented
875 (this latter object may not be a Boolean).
876*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000877PyObject *
878PyObject_RichCompare(PyObject *v, PyObject *w, int op)
879{
880 PyObject *res;
881
882 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000883 if (Py_EnterRecursiveCall(" in cmp"))
884 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000885
Armin Rigo2b3eb402003-10-28 12:05:48 +0000886 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000887 get out cheap (don't bother with coercions etc.). */
888 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
889 cmpfunc fcmp;
890 richcmpfunc frich = RICHCOMPARE(v->ob_type);
891 /* If the type has richcmp, try it first. try_rich_compare
892 tries it two-sided, which is not needed since we've a
893 single type only. */
894 if (frich != NULL) {
895 res = (*frich)(v, w, op);
896 if (res != Py_NotImplemented)
897 goto Done;
898 Py_DECREF(res);
899 }
900 /* No richcmp, or this particular richmp not implemented.
901 Try 3-way cmp. */
902 fcmp = v->ob_type->tp_compare;
903 if (fcmp != NULL) {
904 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000905 c = adjust_tp_compare(c);
906 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000907 res = NULL;
908 goto Done;
909 }
910 res = convert_3way_to_object(op, c);
911 goto Done;
912 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000913 }
Tim Peters67754e92001-11-04 07:29:31 +0000914
915 /* Fast path not taken, or couldn't deliver a useful result. */
916 res = do_richcmp(v, w, op);
917Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000918 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000919 return res;
920}
921
Tim Petersde9725f2001-05-05 10:06:17 +0000922/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000923int
924PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
925{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000926 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000927 int ok;
928
Raymond Hettinger93d44812004-03-21 17:01:44 +0000929 /* Quick result when objects are the same.
930 Guarantees that identity implies equality. */
931 if (v == w) {
932 if (op == Py_EQ)
933 return 1;
934 else if (op == Py_NE)
935 return 0;
936 }
937
938 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000939 if (res == NULL)
940 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000941 if (PyBool_Check(res))
942 ok = (res == Py_True);
943 else
944 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000945 Py_DECREF(res);
946 return ok;
947}
Fred Drake13634cf2000-06-29 19:17:04 +0000948
949/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000950 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000951
952 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
953*/
954
955long
Fred Drake100814d2000-07-09 15:48:49 +0000956_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000957{
Tim Peters39dce292000-08-15 03:34:48 +0000958 double intpart, fractpart;
959 int expo;
960 long hipart;
961 long x; /* the final hash value */
962 /* This is designed so that Python numbers of different types
963 * that compare equal hash to the same value; otherwise comparisons
964 * of mapping keys will turn out weird.
965 */
966
Tim Peters39dce292000-08-15 03:34:48 +0000967 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000968 if (fractpart == 0.0) {
969 /* This must return the same hash as an equal int or long. */
970 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
971 /* Convert to long and use its hash. */
972 PyObject *plong; /* converted to Python long */
973 if (Py_IS_INFINITY(intpart))
974 /* can't convert to long int -- arbitrary */
975 v = v < 0 ? -271828.0 : 314159.0;
976 plong = PyLong_FromDouble(v);
977 if (plong == NULL)
978 return -1;
979 x = PyObject_Hash(plong);
980 Py_DECREF(plong);
981 return x;
982 }
983 /* Fits in a C long == a Python int, so is its own hash. */
984 x = (long)intpart;
985 if (x == -1)
986 x = -2;
987 return x;
988 }
989 /* The fractional part is non-zero, so we don't have to worry about
990 * making this match the hash of some other type.
991 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000992 * Since the VAX D double format has 56 mantissa bits, which is the
993 * most of any double format in use, each of these parts may have as
994 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000995 * So, assuming sizeof(long) >= 4, each part can be broken into two
996 * longs; frexp and multiplication are used to do that.
997 * Also, since the Cray double format has 15 exponent bits, which is
998 * the most of any double format in use, shifting the exponent field
999 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001000 */
Tim Peters39dce292000-08-15 03:34:48 +00001001 v = frexp(v, &expo);
1002 v *= 2147483648.0; /* 2**31 */
1003 hipart = (long)v; /* take the top 32 bits */
1004 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1005 x = hipart + (long)v + (expo << 15);
1006 if (x == -1)
1007 x = -2;
1008 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001009}
1010
1011long
Fred Drake100814d2000-07-09 15:48:49 +00001012_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001013{
1014#if SIZEOF_LONG >= SIZEOF_VOID_P
1015 return (long)p;
1016#else
1017 /* convert to a Python long and hash that */
1018 PyObject* longobj;
1019 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001020
Fred Drake13634cf2000-06-29 19:17:04 +00001021 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1022 x = -1;
1023 goto finally;
1024 }
1025 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001026
Fred Drake13634cf2000-06-29 19:17:04 +00001027finally:
1028 Py_XDECREF(longobj);
1029 return x;
1030#endif
1031}
1032
1033
Guido van Rossum9bfef441993-03-29 10:43:31 +00001034long
Fred Drake100814d2000-07-09 15:48:49 +00001035PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001036{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001037 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001038 if (tp->tp_hash != NULL)
1039 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001040 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001041 return _Py_HashPointer(v); /* Use address as hash value */
1042 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001043 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001044 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001045 return -1;
1046}
1047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001048PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001049PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001050{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001052
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001054 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001055 w = PyString_InternFromString(name);
1056 if (w == NULL)
1057 return NULL;
1058 res = PyObject_GetAttr(v, w);
1059 Py_XDECREF(w);
1060 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001061}
1062
1063int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001064PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001065{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001066 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001067 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001068 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001069 return 1;
1070 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001071 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001072 return 0;
1073}
1074
1075int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001076PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001077{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078 PyObject *s;
1079 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001080
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001082 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 s = PyString_InternFromString(name);
1084 if (s == NULL)
1085 return -1;
1086 res = PyObject_SetAttr(v, s, w);
1087 Py_XDECREF(s);
1088 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001089}
1090
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001091PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001092PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001093{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094 PyTypeObject *tp = v->ob_type;
1095
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001096 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001097#ifdef Py_USING_UNICODE
1098 /* The Unicode to string conversion is done here because the
1099 existing tp_getattro slots expect a string object as name
1100 and we wouldn't want to break those. */
1101 if (PyUnicode_Check(name)) {
1102 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1103 if (name == NULL)
1104 return NULL;
1105 }
1106 else
1107#endif
1108 {
1109 PyErr_SetString(PyExc_TypeError,
1110 "attribute name must be string");
1111 return NULL;
1112 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001113 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114 if (tp->tp_getattro != NULL)
1115 return (*tp->tp_getattro)(v, name);
1116 if (tp->tp_getattr != NULL)
1117 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1118 PyErr_Format(PyExc_AttributeError,
1119 "'%.50s' object has no attribute '%.400s'",
1120 tp->tp_name, PyString_AS_STRING(name));
1121 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001122}
1123
1124int
Fred Drake100814d2000-07-09 15:48:49 +00001125PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001126{
1127 PyObject *res = PyObject_GetAttr(v, name);
1128 if (res != NULL) {
1129 Py_DECREF(res);
1130 return 1;
1131 }
1132 PyErr_Clear();
1133 return 0;
1134}
1135
1136int
Fred Drake100814d2000-07-09 15:48:49 +00001137PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001138{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001140 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001141
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001142 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001143#ifdef Py_USING_UNICODE
1144 /* The Unicode to string conversion is done here because the
1145 existing tp_setattro slots expect a string object as name
1146 and we wouldn't want to break those. */
1147 if (PyUnicode_Check(name)) {
1148 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1149 if (name == NULL)
1150 return -1;
1151 }
Tim Peters803526b2002-07-07 05:13:56 +00001152 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001153#endif
1154 {
1155 PyErr_SetString(PyExc_TypeError,
1156 "attribute name must be string");
1157 return -1;
1158 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001159 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160 else
1161 Py_INCREF(name);
1162
1163 PyString_InternInPlace(&name);
1164 if (tp->tp_setattro != NULL) {
1165 err = (*tp->tp_setattro)(v, name, value);
1166 Py_DECREF(name);
1167 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001168 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 if (tp->tp_setattr != NULL) {
1170 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1171 Py_DECREF(name);
1172 return err;
1173 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001174 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1176 PyErr_Format(PyExc_TypeError,
1177 "'%.100s' object has no attributes "
1178 "(%s .%.100s)",
1179 tp->tp_name,
1180 value==NULL ? "del" : "assign to",
1181 PyString_AS_STRING(name));
1182 else
1183 PyErr_Format(PyExc_TypeError,
1184 "'%.100s' object has only read-only attributes "
1185 "(%s .%.100s)",
1186 tp->tp_name,
1187 value==NULL ? "del" : "assign to",
1188 PyString_AS_STRING(name));
1189 return -1;
1190}
1191
1192/* Helper to get a pointer to an object's __dict__ slot, if any */
1193
1194PyObject **
1195_PyObject_GetDictPtr(PyObject *obj)
1196{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001197 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001198 PyTypeObject *tp = obj->ob_type;
1199
1200 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1201 return NULL;
1202 dictoffset = tp->tp_dictoffset;
1203 if (dictoffset == 0)
1204 return NULL;
1205 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001206 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001207 size_t size;
1208
1209 tsize = ((PyVarObject *)obj)->ob_size;
1210 if (tsize < 0)
1211 tsize = -tsize;
1212 size = _PyObject_VAR_SIZE(tp, tsize);
1213
Tim Peters6d483d32001-10-06 21:27:34 +00001214 dictoffset += (long)size;
1215 assert(dictoffset > 0);
1216 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217 }
1218 return (PyObject **) ((char *)obj + dictoffset);
1219}
1220
Tim Peters6d6c1a32001-08-02 04:15:00 +00001221PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001222PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001223{
1224 Py_INCREF(obj);
1225 return obj;
1226}
1227
Michael W. Hudson1593f502004-09-14 17:09:47 +00001228/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1229
Raymond Hettinger01538262003-03-17 08:24:35 +00001230PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001231PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1232{
1233 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001234 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001235 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001237 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 PyObject **dictptr;
1239
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001240 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001241#ifdef Py_USING_UNICODE
1242 /* The Unicode to string conversion is done here because the
1243 existing tp_setattro slots expect a string object as name
1244 and we wouldn't want to break those. */
1245 if (PyUnicode_Check(name)) {
1246 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1247 if (name == NULL)
1248 return NULL;
1249 }
Tim Peters803526b2002-07-07 05:13:56 +00001250 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001251#endif
1252 {
1253 PyErr_SetString(PyExc_TypeError,
1254 "attribute name must be string");
1255 return NULL;
1256 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001257 }
1258 else
1259 Py_INCREF(name);
1260
Tim Peters6d6c1a32001-08-02 04:15:00 +00001261 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001262 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001263 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264 }
1265
Guido van Rossum056fbf42002-08-19 19:22:50 +00001266 /* Inline _PyType_Lookup */
1267 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001268 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001269 PyObject *mro, *base, *dict;
1270
1271 /* Look in tp_dict of types in MRO */
1272 mro = tp->tp_mro;
1273 assert(mro != NULL);
1274 assert(PyTuple_Check(mro));
1275 n = PyTuple_GET_SIZE(mro);
1276 for (i = 0; i < n; i++) {
1277 base = PyTuple_GET_ITEM(mro, i);
1278 if (PyClass_Check(base))
1279 dict = ((PyClassObject *)base)->cl_dict;
1280 else {
1281 assert(PyType_Check(base));
1282 dict = ((PyTypeObject *)base)->tp_dict;
1283 }
1284 assert(dict && PyDict_Check(dict));
1285 descr = PyDict_GetItem(dict, name);
1286 if (descr != NULL)
1287 break;
1288 }
1289 }
1290
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001291 Py_XINCREF(descr);
1292
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001294 if (descr != NULL &&
1295 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001297 if (f != NULL && PyDescr_IsData(descr)) {
1298 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001299 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001300 goto done;
1301 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302 }
1303
Guido van Rossumc66ff442002-08-19 16:50:48 +00001304 /* Inline _PyObject_GetDictPtr */
1305 dictoffset = tp->tp_dictoffset;
1306 if (dictoffset != 0) {
1307 PyObject *dict;
1308 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001309 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001310 size_t size;
1311
1312 tsize = ((PyVarObject *)obj)->ob_size;
1313 if (tsize < 0)
1314 tsize = -tsize;
1315 size = _PyObject_VAR_SIZE(tp, tsize);
1316
1317 dictoffset += (long)size;
1318 assert(dictoffset > 0);
1319 assert(dictoffset % SIZEOF_VOID_P == 0);
1320 }
1321 dictptr = (PyObject **) ((char *)obj + dictoffset);
1322 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001324 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 if (res != NULL) {
1326 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001327 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001328 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 }
1330 }
1331 }
1332
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001333 if (f != NULL) {
1334 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001335 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001336 goto done;
1337 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338
1339 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001340 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001341 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001342 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343 }
1344
1345 PyErr_Format(PyExc_AttributeError,
1346 "'%.50s' object has no attribute '%.400s'",
1347 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001348 done:
1349 Py_DECREF(name);
1350 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001351}
1352
1353int
1354PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1355{
1356 PyTypeObject *tp = obj->ob_type;
1357 PyObject *descr;
1358 descrsetfunc f;
1359 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001360 int res = -1;
1361
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001362 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001363#ifdef Py_USING_UNICODE
1364 /* The Unicode to string conversion is done here because the
1365 existing tp_setattro slots expect a string object as name
1366 and we wouldn't want to break those. */
1367 if (PyUnicode_Check(name)) {
1368 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1369 if (name == NULL)
1370 return -1;
1371 }
Tim Peters803526b2002-07-07 05:13:56 +00001372 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001373#endif
1374 {
1375 PyErr_SetString(PyExc_TypeError,
1376 "attribute name must be string");
1377 return -1;
1378 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001379 }
1380 else
1381 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001382
1383 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001384 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001385 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 }
1387
1388 descr = _PyType_Lookup(tp, name);
1389 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001390 if (descr != NULL &&
1391 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001393 if (f != NULL && PyDescr_IsData(descr)) {
1394 res = f(descr, obj, value);
1395 goto done;
1396 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 }
1398
1399 dictptr = _PyObject_GetDictPtr(obj);
1400 if (dictptr != NULL) {
1401 PyObject *dict = *dictptr;
1402 if (dict == NULL && value != NULL) {
1403 dict = PyDict_New();
1404 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001405 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406 *dictptr = dict;
1407 }
1408 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409 if (value == NULL)
1410 res = PyDict_DelItem(dict, name);
1411 else
1412 res = PyDict_SetItem(dict, name, value);
1413 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1414 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001415 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001416 }
1417 }
1418
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001419 if (f != NULL) {
1420 res = f(descr, obj, value);
1421 goto done;
1422 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001423
1424 if (descr == NULL) {
1425 PyErr_Format(PyExc_AttributeError,
1426 "'%.50s' object has no attribute '%.400s'",
1427 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001428 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429 }
1430
1431 PyErr_Format(PyExc_AttributeError,
1432 "'%.50s' object attribute '%.400s' is read-only",
1433 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001434 done:
1435 Py_DECREF(name);
1436 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001437}
1438
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001439/* Test a value used as condition, e.g., in a for or if statement.
1440 Return -1 if an error occurred */
1441
1442int
Fred Drake100814d2000-07-09 15:48:49 +00001443PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001444{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001445 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001446 if (v == Py_True)
1447 return 1;
1448 if (v == Py_False)
1449 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001450 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001451 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001452 else if (v->ob_type->tp_as_number != NULL &&
1453 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001454 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001455 else if (v->ob_type->tp_as_mapping != NULL &&
1456 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001457 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001458 else if (v->ob_type->tp_as_sequence != NULL &&
1459 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001460 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1461 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001462 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001463 /* if it is negative, it should be either -1 or -2 */
1464 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001465}
1466
Tim Peters803526b2002-07-07 05:13:56 +00001467/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001468 Return -1 if an error occurred */
1469
1470int
Fred Drake100814d2000-07-09 15:48:49 +00001471PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001472{
1473 int res;
1474 res = PyObject_IsTrue(v);
1475 if (res < 0)
1476 return res;
1477 return res == 0;
1478}
1479
Guido van Rossum5524a591995-01-10 15:26:20 +00001480/* Coerce two numeric types to the "larger" one.
1481 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001482 Return value:
1483 -1 if an error occurred;
1484 0 if the coercion succeeded (and then the reference counts are increased);
1485 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001486*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001487int
Fred Drake100814d2000-07-09 15:48:49 +00001488PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001489{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490 register PyObject *v = *pv;
1491 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001492 int res;
1493
Guido van Rossum517c7d42002-04-26 02:49:14 +00001494 /* Shortcut only for old-style types */
1495 if (v->ob_type == w->ob_type &&
1496 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1497 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001498 Py_INCREF(v);
1499 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001500 return 0;
1501 }
1502 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1503 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1504 if (res <= 0)
1505 return res;
1506 }
1507 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1508 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1509 if (res <= 0)
1510 return res;
1511 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001512 return 1;
1513}
1514
Guido van Rossume797ec12001-01-17 15:24:28 +00001515/* Coerce two numeric types to the "larger" one.
1516 Increment the reference count on each argument.
1517 Return -1 and raise an exception if no coercion is possible
1518 (and then no reference count is incremented).
1519*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001520int
Fred Drake100814d2000-07-09 15:48:49 +00001521PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001522{
1523 int err = PyNumber_CoerceEx(pv, pw);
1524 if (err <= 0)
1525 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001526 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001527 return -1;
1528}
1529
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001531/* Test whether an object can be called */
1532
1533int
Fred Drake100814d2000-07-09 15:48:49 +00001534PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001535{
1536 if (x == NULL)
1537 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001538 if (PyInstance_Check(x)) {
1539 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001540 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001541 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001542 return 0;
1543 }
1544 /* Could test recursively but don't, for fear of endless
1545 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001546 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001547 return 1;
1548 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001549 else {
1550 return x->ob_type->tp_call != NULL;
1551 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001552}
1553
Tim Peters7eea37e2001-09-04 22:08:56 +00001554/* Helper for PyObject_Dir.
1555 Merge the __dict__ of aclass into dict, and recursively also all
1556 the __dict__s of aclass's base classes. The order of merging isn't
1557 defined, as it's expected that only the final set of dict keys is
1558 interesting.
1559 Return 0 on success, -1 on error.
1560*/
1561
1562static int
1563merge_class_dict(PyObject* dict, PyObject* aclass)
1564{
1565 PyObject *classdict;
1566 PyObject *bases;
1567
1568 assert(PyDict_Check(dict));
1569 assert(aclass);
1570
1571 /* Merge in the type's dict (if any). */
1572 classdict = PyObject_GetAttrString(aclass, "__dict__");
1573 if (classdict == NULL)
1574 PyErr_Clear();
1575 else {
1576 int status = PyDict_Update(dict, classdict);
1577 Py_DECREF(classdict);
1578 if (status < 0)
1579 return -1;
1580 }
1581
1582 /* Recursively merge in the base types' (if any) dicts. */
1583 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001584 if (bases == NULL)
1585 PyErr_Clear();
1586 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001587 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001588 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001589 n = PySequence_Size(bases); /* This better be right */
1590 if (n < 0)
1591 PyErr_Clear();
1592 else {
1593 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001594 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001595 PyObject *base = PySequence_GetItem(bases, i);
1596 if (base == NULL) {
1597 Py_DECREF(bases);
1598 return -1;
1599 }
Tim Peters18e70832003-02-05 19:35:19 +00001600 status = merge_class_dict(dict, base);
1601 Py_DECREF(base);
1602 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001603 Py_DECREF(bases);
1604 return -1;
1605 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001606 }
1607 }
1608 Py_DECREF(bases);
1609 }
1610 return 0;
1611}
1612
Tim Peters305b5852001-09-17 02:38:46 +00001613/* Helper for PyObject_Dir.
1614 If obj has an attr named attrname that's a list, merge its string
1615 elements into keys of dict.
1616 Return 0 on success, -1 on error. Errors due to not finding the attr,
1617 or the attr not being a list, are suppressed.
1618*/
1619
1620static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001621merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001622{
1623 PyObject *list;
1624 int result = 0;
1625
1626 assert(PyDict_Check(dict));
1627 assert(obj);
1628 assert(attrname);
1629
1630 list = PyObject_GetAttrString(obj, attrname);
1631 if (list == NULL)
1632 PyErr_Clear();
1633
1634 else if (PyList_Check(list)) {
1635 int i;
1636 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1637 PyObject *item = PyList_GET_ITEM(list, i);
1638 if (PyString_Check(item)) {
1639 result = PyDict_SetItem(dict, item, Py_None);
1640 if (result < 0)
1641 break;
1642 }
1643 }
1644 }
1645
1646 Py_XDECREF(list);
1647 return result;
1648}
1649
Tim Peters7eea37e2001-09-04 22:08:56 +00001650/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1651 docstring, which should be kept in synch with this implementation. */
1652
1653PyObject *
1654PyObject_Dir(PyObject *arg)
1655{
1656 /* Set exactly one of these non-NULL before the end. */
1657 PyObject *result = NULL; /* result list */
1658 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1659
1660 /* If NULL arg, return the locals. */
1661 if (arg == NULL) {
1662 PyObject *locals = PyEval_GetLocals();
1663 if (locals == NULL)
1664 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001665 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001666 if (result == NULL)
1667 goto error;
1668 }
1669
1670 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001671 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001672 masterdict = PyObject_GetAttrString(arg, "__dict__");
1673 if (masterdict == NULL)
1674 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001675 if (!PyDict_Check(masterdict)) {
1676 PyErr_SetString(PyExc_TypeError,
1677 "module.__dict__ is not a dictionary");
1678 goto error;
1679 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001680 }
1681
1682 /* Elif some form of type or class, grab its dict and its bases.
1683 We deliberately don't suck up its __class__, as methods belonging
1684 to the metaclass would probably be more confusing than helpful. */
1685 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1686 masterdict = PyDict_New();
1687 if (masterdict == NULL)
1688 goto error;
1689 if (merge_class_dict(masterdict, arg) < 0)
1690 goto error;
1691 }
1692
1693 /* Else look at its dict, and the attrs reachable from its class. */
1694 else {
1695 PyObject *itsclass;
1696 /* Create a dict to start with. CAUTION: Not everything
1697 responding to __dict__ returns a dict! */
1698 masterdict = PyObject_GetAttrString(arg, "__dict__");
1699 if (masterdict == NULL) {
1700 PyErr_Clear();
1701 masterdict = PyDict_New();
1702 }
1703 else if (!PyDict_Check(masterdict)) {
1704 Py_DECREF(masterdict);
1705 masterdict = PyDict_New();
1706 }
1707 else {
1708 /* The object may have returned a reference to its
1709 dict, so copy it to avoid mutating it. */
1710 PyObject *temp = PyDict_Copy(masterdict);
1711 Py_DECREF(masterdict);
1712 masterdict = temp;
1713 }
1714 if (masterdict == NULL)
1715 goto error;
1716
Tim Peters305b5852001-09-17 02:38:46 +00001717 /* Merge in __members__ and __methods__ (if any).
1718 XXX Would like this to go away someday; for now, it's
1719 XXX needed to get at im_self etc of method objects. */
1720 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1721 goto error;
1722 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1723 goto error;
1724
Tim Peters7eea37e2001-09-04 22:08:56 +00001725 /* Merge in attrs reachable from its class.
1726 CAUTION: Not all objects have a __class__ attr. */
1727 itsclass = PyObject_GetAttrString(arg, "__class__");
1728 if (itsclass == NULL)
1729 PyErr_Clear();
1730 else {
1731 int status = merge_class_dict(masterdict, itsclass);
1732 Py_DECREF(itsclass);
1733 if (status < 0)
1734 goto error;
1735 }
1736 }
1737
1738 assert((result == NULL) ^ (masterdict == NULL));
1739 if (masterdict != NULL) {
1740 /* The result comes from its keys. */
1741 assert(result == NULL);
1742 result = PyDict_Keys(masterdict);
1743 if (result == NULL)
1744 goto error;
1745 }
1746
1747 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001748 if (!PyList_Check(result)) {
Tim Petersf4aca752004-09-23 02:39:37 +00001749 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001750 "Expected keys() to be a list.");
1751 goto error;
1752 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001753 if (PyList_Sort(result) != 0)
1754 goto error;
1755 else
1756 goto normal_return;
1757
1758 error:
1759 Py_XDECREF(result);
1760 result = NULL;
1761 /* fall through */
1762 normal_return:
1763 Py_XDECREF(masterdict);
1764 return result;
1765}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001766
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001767/*
1768NoObject is usable as a non-NULL undefined value, used by the macro None.
1769There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001770so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001771(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001772*/
1773
Guido van Rossum0c182a11992-03-27 17:26:13 +00001774/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001775static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001776none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001777{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001778 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001779}
1780
Barry Warsaw9bf16442001-01-23 16:24:35 +00001781/* ARGUSED */
1782static void
Tim Peters803526b2002-07-07 05:13:56 +00001783none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001784{
1785 /* This should never get called, but we also don't want to SEGV if
1786 * we accidently decref None out of existance.
1787 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001788 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001789}
1790
1791
Guido van Rossumba21a492001-08-16 08:17:26 +00001792static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001793 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001794 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001795 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001796 0,
1797 0,
Georg Brandl347b3002006-03-30 11:57:00 +00001798 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001799 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001800 0, /*tp_getattr*/
1801 0, /*tp_setattr*/
1802 0, /*tp_compare*/
Georg Brandl347b3002006-03-30 11:57:00 +00001803 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001804 0, /*tp_as_number*/
1805 0, /*tp_as_sequence*/
1806 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001807 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001808};
1809
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001810PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001811 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001812};
1813
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001814/* NotImplemented is an object that can be used to signal that an
1815 operation is not implemented for the given type combination. */
1816
1817static PyObject *
1818NotImplemented_repr(PyObject *op)
1819{
1820 return PyString_FromString("NotImplemented");
1821}
1822
1823static PyTypeObject PyNotImplemented_Type = {
1824 PyObject_HEAD_INIT(&PyType_Type)
1825 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001826 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001827 0,
1828 0,
Georg Brandl347b3002006-03-30 11:57:00 +00001829 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001830 0, /*tp_print*/
1831 0, /*tp_getattr*/
1832 0, /*tp_setattr*/
1833 0, /*tp_compare*/
Georg Brandl347b3002006-03-30 11:57:00 +00001834 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001835 0, /*tp_as_number*/
1836 0, /*tp_as_sequence*/
1837 0, /*tp_as_mapping*/
1838 0, /*tp_hash */
1839};
1840
1841PyObject _Py_NotImplementedStruct = {
1842 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1843};
1844
Guido van Rossumba21a492001-08-16 08:17:26 +00001845void
1846_Py_ReadyTypes(void)
1847{
1848 if (PyType_Ready(&PyType_Type) < 0)
1849 Py_FatalError("Can't initialize 'type'");
1850
Fred Drake0a4dd392004-07-02 18:57:45 +00001851 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1852 Py_FatalError("Can't initialize 'weakref'");
1853
Guido van Rossum77f6a652002-04-03 22:41:51 +00001854 if (PyType_Ready(&PyBool_Type) < 0)
1855 Py_FatalError("Can't initialize 'bool'");
1856
Guido van Rossumcacfc072002-05-24 19:01:59 +00001857 if (PyType_Ready(&PyString_Type) < 0)
1858 Py_FatalError("Can't initialize 'str'");
1859
Guido van Rossumba21a492001-08-16 08:17:26 +00001860 if (PyType_Ready(&PyList_Type) < 0)
1861 Py_FatalError("Can't initialize 'list'");
1862
1863 if (PyType_Ready(&PyNone_Type) < 0)
1864 Py_FatalError("Can't initialize type(None)");
1865
1866 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1867 Py_FatalError("Can't initialize type(NotImplemented)");
1868}
1869
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001870
Guido van Rossum84a90321996-05-22 16:34:47 +00001871#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001872
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001873void
Fred Drake100814d2000-07-09 15:48:49 +00001874_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001875{
Tim Peters34592512002-07-11 06:23:50 +00001876 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001877 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001878 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001879 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880}
1881
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001882void
Fred Drake100814d2000-07-09 15:48:49 +00001883_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001884{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001885#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001886 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001887#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001888 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001889 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001890 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001891 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001892 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001893#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001894 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1895 if (p == op)
1896 break;
1897 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001898 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001899 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001900#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001901 op->_ob_next->_ob_prev = op->_ob_prev;
1902 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001903 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001904 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001905}
1906
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001907void
Fred Drake100814d2000-07-09 15:48:49 +00001908_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001909{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001910 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001912 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001913}
1914
Tim Peters269b2a62003-04-17 19:52:29 +00001915/* Print all live objects. Because PyObject_Print is called, the
1916 * interpreter must be in a healthy state.
1917 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001918void
Fred Drake100814d2000-07-09 15:48:49 +00001919_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001920{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001921 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001922 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001923 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peterscbd6f182006-04-11 19:12:33 +00001924 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001925 if (PyObject_Print(op, fp, 0) != 0)
1926 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001927 putc('\n', fp);
1928 }
1929}
1930
Tim Peters269b2a62003-04-17 19:52:29 +00001931/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1932 * doesn't make any calls to the Python C API, so is always safe to call.
1933 */
1934void
1935_Py_PrintReferenceAddresses(FILE *fp)
1936{
1937 PyObject *op;
1938 fprintf(fp, "Remaining object addresses:\n");
1939 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peterscbd6f182006-04-11 19:12:33 +00001940 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1941 op->ob_refcnt, op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001942}
1943
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001944PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001945_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001946{
1947 int i, n;
1948 PyObject *t = NULL;
1949 PyObject *res, *op;
1950
1951 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1952 return NULL;
1953 op = refchain._ob_next;
1954 res = PyList_New(0);
1955 if (res == NULL)
1956 return NULL;
1957 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1958 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001959 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001960 op = op->_ob_next;
1961 if (op == &refchain)
1962 return res;
1963 }
1964 if (PyList_Append(res, op) < 0) {
1965 Py_DECREF(res);
1966 return NULL;
1967 }
1968 op = op->_ob_next;
1969 }
1970 return res;
1971}
1972
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001973#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001974
1975
1976/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001977PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001978
1979
1980/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001981Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001982
1983
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001984/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001985
Thomas Wouters334fb892000-07-25 12:56:38 +00001986void *
Fred Drake100814d2000-07-09 15:48:49 +00001987PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001988{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001989 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001990}
1991
Thomas Wouters334fb892000-07-25 12:56:38 +00001992void *
1993PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001994{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001995 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001996}
1997
1998void
Thomas Wouters334fb892000-07-25 12:56:38 +00001999PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002000{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002001 PyMem_FREE(p);
2002}
2003
2004
Guido van Rossum86610361998-04-10 22:32:46 +00002005/* These methods are used to control infinite recursion in repr, str, print,
2006 etc. Container objects that may recursively contain themselves,
2007 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2008 Py_ReprLeave() to avoid infinite recursion.
2009
2010 Py_ReprEnter() returns 0 the first time it is called for a particular
2011 object and 1 every time thereafter. It returns -1 if an exception
2012 occurred. Py_ReprLeave() has no return value.
2013
2014 See dictobject.c and listobject.c for examples of use.
2015*/
2016
2017#define KEY "Py_Repr"
2018
2019int
Fred Drake100814d2000-07-09 15:48:49 +00002020Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002021{
2022 PyObject *dict;
2023 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002024 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002025
2026 dict = PyThreadState_GetDict();
2027 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00002028 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002029 list = PyDict_GetItemString(dict, KEY);
2030 if (list == NULL) {
2031 list = PyList_New(0);
2032 if (list == NULL)
2033 return -1;
2034 if (PyDict_SetItemString(dict, KEY, list) < 0)
2035 return -1;
2036 Py_DECREF(list);
2037 }
2038 i = PyList_GET_SIZE(list);
2039 while (--i >= 0) {
2040 if (PyList_GET_ITEM(list, i) == obj)
2041 return 1;
2042 }
2043 PyList_Append(list, obj);
2044 return 0;
2045}
2046
2047void
Fred Drake100814d2000-07-09 15:48:49 +00002048Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002049{
2050 PyObject *dict;
2051 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002052 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002053
2054 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002055 if (dict == NULL)
2056 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002057 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002058 if (list == NULL || !PyList_Check(list))
2059 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002060 i = PyList_GET_SIZE(list);
2061 /* Count backwards because we always expect obj to be list[-1] */
2062 while (--i >= 0) {
2063 if (PyList_GET_ITEM(list, i) == obj) {
2064 PyList_SetSlice(list, i, i + 1, NULL);
2065 break;
2066 }
2067 }
2068}
Guido van Rossumd724b232000-03-13 16:01:29 +00002069
Tim Peters803526b2002-07-07 05:13:56 +00002070/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002071
Tim Peters803526b2002-07-07 05:13:56 +00002072/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002073int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002074
Tim Peters803526b2002-07-07 05:13:56 +00002075/* List of objects that still need to be cleaned up, singly linked via their
2076 * gc headers' gc_prev pointers.
2077 */
2078PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002079
Tim Peters803526b2002-07-07 05:13:56 +00002080/* Add op to the _PyTrash_delete_later list. Called when the current
2081 * call-stack depth gets large. op must be a currently untracked gc'ed
2082 * object, with refcount 0. Py_DECREF must already have been called on it.
2083 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002084void
Fred Drake100814d2000-07-09 15:48:49 +00002085_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002086{
Tim Peters803526b2002-07-07 05:13:56 +00002087 assert(PyObject_IS_GC(op));
2088 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2089 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002090 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002091 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002092}
2093
Tim Peters803526b2002-07-07 05:13:56 +00002094/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2095 * the call-stack unwinds again.
2096 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002097void
Fred Drake100814d2000-07-09 15:48:49 +00002098_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002099{
2100 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002101 PyObject *op = _PyTrash_delete_later;
2102 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002103
Neil Schemenauerf589c052002-03-29 03:05:54 +00002104 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002105 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002106
Tim Peters803526b2002-07-07 05:13:56 +00002107 /* Call the deallocator directly. This used to try to
2108 * fool Py_DECREF into calling it indirectly, but
2109 * Py_DECREF was already called on this object, and in
2110 * assorted non-release builds calling Py_DECREF again ends
2111 * up distorting allocation statistics.
2112 */
2113 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002114 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002115 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002116 --_PyTrash_delete_nesting;
2117 }
2118}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002119
2120#ifdef __cplusplus
2121}
2122#endif
2123