blob: 0d317b2388918d330b139853ffe905e057a7b2bd [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 Rossum50e9fb92006-08-17 05:42:55 +00005#include "sliceobject.h" /* For PyEllipsis_Type */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#ifdef __cplusplus
8extern "C" {
9#endif
10
Tim Peters34592512002-07-11 06:23:50 +000011#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000012Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013
14Py_ssize_t
15_Py_GetRefTotal(void)
16{
17 PyObject *o;
18 Py_ssize_t total = _Py_RefTotal;
19 /* ignore the references to the dummy object of the dicts and sets
20 because they are not reliable and not useful (now that the
21 hash table code is well-tested) */
22 o = _PyDict_Dummy();
23 if (o != NULL)
24 total -= o->ob_refcnt;
25 o = _PySet_Dummy();
26 if (o != NULL)
27 total -= o->ob_refcnt;
28 return total;
29}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Mark Hammonda2905272002-07-29 13:42:14 +000032int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000033
Guido van Rossum3f5da241990-12-20 15:06:42 +000034/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
35 These are used by the individual routines for object creation.
36 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037
Tim Peters78be7992003-03-23 02:51:01 +000038#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000039/* Head of circular doubly-linked list of all objects. These are linked
40 * together via the _ob_prev and _ob_next members of a PyObject, which
41 * exist only in a Py_TRACE_REFS build.
42 */
Tim Peters78be7992003-03-23 02:51:01 +000043static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000044
Tim Peters7571a0f2003-03-23 17:52:28 +000045/* Insert op at the front of the list of all objects. If force is true,
46 * op is added even if _ob_prev and _ob_next are non-NULL already. If
47 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
48 * force should be true if and only if op points to freshly allocated,
49 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000050 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000051 * Note that objects are normally added to the list via _Py_NewReference,
52 * which is called by PyObject_Init. Not all objects are initialized that
53 * way, though; exceptions include statically allocated type objects, and
54 * statically allocated singletons (like Py_True and Py_None).
55 */
Tim Peters36eb4df2003-03-23 03:33:13 +000056void
Tim Peters7571a0f2003-03-23 17:52:28 +000057_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000058{
Tim Peters7571a0f2003-03-23 17:52:28 +000059#ifdef Py_DEBUG
60 if (!force) {
61 /* If it's initialized memory, op must be in or out of
62 * the list unambiguously.
63 */
64 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
65 }
Tim Peters78be7992003-03-23 02:51:01 +000066#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000067 if (force || op->_ob_prev == NULL) {
68 op->_ob_next = refchain._ob_next;
69 op->_ob_prev = &refchain;
70 refchain._ob_next->_ob_prev = op;
71 refchain._ob_next = op;
72 }
73}
74#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000075
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078/* All types are added to type_list, at least when
79 they get one object created. That makes them
80 immortal, which unfortunately contributes to
81 garbage itself. If unlist_types_without_objects
82 is set, they will be removed from the type_list
83 once the last object is deallocated. */
84int unlist_types_without_objects;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000085extern int tuple_zero_allocs, fast_tuple_allocs;
86extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000087extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000088void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000090{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000092
93 for (tp = type_list; tp; tp = tp->tp_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094 fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000095 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000096 tp->tp_maxalloc);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000097 fprintf(f, "fast tuple allocs: %d, empty: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000098 fast_tuple_allocs, tuple_zero_allocs);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000099 fprintf(f, "fast int allocs: pos: %d, neg: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +0000100 quick_int_allocs, quick_neg_int_allocs);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101 fprintf(f, "null strings: %d, 1-strings: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +0000102 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000103}
104
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000105PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000106get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000107{
108 PyTypeObject *tp;
109 PyObject *result;
110 PyObject *v;
111
112 result = PyList_New(0);
113 if (result == NULL)
114 return NULL;
115 for (tp = type_list; tp; tp = tp->tp_next) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000116 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000117 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000118 if (v == NULL) {
119 Py_DECREF(result);
120 return NULL;
121 }
122 if (PyList_Append(result, v) < 0) {
123 Py_DECREF(v);
124 Py_DECREF(result);
125 return NULL;
126 }
127 Py_DECREF(v);
128 }
129 return result;
130}
131
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000132void
Fred Drake100814d2000-07-09 15:48:49 +0000133inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000134{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000135 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000136 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 Py_FatalError("XXX inc_count sanity check");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000139 if (type_list)
140 type_list->tp_prev = tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000141 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000142 /* Note that as of Python 2.2, heap-allocated type objects
143 * can go away, but this code requires that they stay alive
144 * until program exit. That's why we're careful with
145 * refcounts here. type_list gets a new reference to tp,
146 * while ownership of the reference type_list used to hold
147 * (if any) was transferred to tp->tp_next in the line above.
148 * tp is thus effectively immortal after this.
149 */
150 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000151 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000152#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000153 /* Also insert in the doubly-linked list of all objects,
154 * if not already there.
155 */
156 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000157#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000158 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000159 tp->tp_allocs++;
160 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
161 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000162}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163
164void dec_count(PyTypeObject *tp)
165{
166 tp->tp_frees++;
167 if (unlist_types_without_objects &&
168 tp->tp_allocs == tp->tp_frees) {
169 /* unlink the type from type_list */
170 if (tp->tp_prev)
171 tp->tp_prev->tp_next = tp->tp_next;
172 else
173 type_list = tp->tp_next;
174 if (tp->tp_next)
175 tp->tp_next->tp_prev = tp->tp_prev;
176 tp->tp_next = tp->tp_prev = NULL;
177 Py_DECREF(tp);
178 }
179}
180
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000181#endif
182
Tim Peters7c321a82002-07-09 02:57:01 +0000183#ifdef Py_REF_DEBUG
184/* Log a fatal error; doesn't return. */
185void
186_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
187{
188 char buf[300];
189
190 PyOS_snprintf(buf, sizeof(buf),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191 "%s:%i object at %p has negative ref count "
192 "%" PY_FORMAT_SIZE_T "d",
193 fname, lineno, op, op->ob_refcnt);
Tim Peters7c321a82002-07-09 02:57:01 +0000194 Py_FatalError(buf);
195}
196
197#endif /* Py_REF_DEBUG */
198
Thomas Heller1328b522004-04-22 17:23:49 +0000199void
200Py_IncRef(PyObject *o)
201{
202 Py_XINCREF(o);
203}
204
205void
206Py_DecRef(PyObject *o)
207{
208 Py_XDECREF(o);
209}
210
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000212PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000214 if (op == NULL)
215 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000216 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Christian Heimes90aa7642007-12-19 02:45:37 +0000217 Py_TYPE(op) = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000218 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219 return op;
220}
221
Guido van Rossumb18618d2000-05-03 23:44:39 +0000222PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000224{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000225 if (op == NULL)
226 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227 /* Any changes should be reflected in PyObject_INIT_VAR */
228 op->ob_size = size;
Christian Heimes90aa7642007-12-19 02:45:37 +0000229 Py_TYPE(op) = tp;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000230 _Py_NewReference((PyObject *)op);
231 return op;
232}
233
234PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000235_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000236{
237 PyObject *op;
238 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
239 if (op == NULL)
240 return PyErr_NoMemory();
241 return PyObject_INIT(op, tp);
242}
243
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000244PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000245_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000247 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000248 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000249 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000251 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000252 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000253}
254
Neal Norwitz1a997502003-01-13 20:13:12 +0000255/* Implementation of PyObject_Print with recursion checking */
256static int
257internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258{
Guido van Rossum278ef591991-07-27 21:40:24 +0000259 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000260 if (nesting > 10) {
261 PyErr_SetString(PyExc_RuntimeError, "print recursion");
262 return -1;
263 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000264 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000265 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000266#ifdef USE_STACKCHECK
267 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000268 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000269 return -1;
270 }
271#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000272 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000273 if (op == NULL) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000274 Py_BEGIN_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000275 fprintf(fp, "<nil>");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000276 Py_END_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277 }
Guido van Rossum90933611991-06-07 16:10:43 +0000278 else {
279 if (op->ob_refcnt <= 0)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000280 /* XXX(twouters) cast refcount to long until %zd is
281 universally available */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000282 Py_BEGIN_ALLOW_THREADS
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000283 fprintf(fp, "<refcnt %ld at %p>",
284 (long)op->ob_refcnt, op);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000285 Py_END_ALLOW_THREADS
Guido van Rossum04dbf3b2007-08-07 19:51:00 +0000286 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000287 PyObject *s;
288 if (flags & Py_PRINT_RAW)
289 s = PyObject_Str(op);
290 else
Guido van Rossum6ca130d2007-08-09 20:47:59 +0000291 s = PyObject_Repr(op);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000292 if (s == NULL)
293 ret = -1;
Guido van Rossum6ca130d2007-08-09 20:47:59 +0000294 else if (PyString_Check(s)) {
295 fwrite(PyString_AS_STRING(s), 1,
296 PyString_GET_SIZE(s), fp);
297 }
298 else if (PyUnicode_Check(s)) {
299 PyObject *t;
300 t = _PyUnicode_AsDefaultEncodedString(s, NULL);
301 if (t == NULL)
302 ret = 0;
303 else {
304 fwrite(PyString_AS_STRING(t), 1,
305 PyString_GET_SIZE(t), fp);
306 }
307 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000308 else {
Guido van Rossum6ca130d2007-08-09 20:47:59 +0000309 PyErr_Format(PyExc_TypeError,
310 "str() or repr() returned '%.100s'",
311 s->ob_type->tp_name);
312 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000313 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000314 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000315 }
Guido van Rossum90933611991-06-07 16:10:43 +0000316 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000317 if (ret == 0) {
318 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000319 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000320 clearerr(fp);
321 ret = -1;
322 }
323 }
324 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325}
326
Neal Norwitz1a997502003-01-13 20:13:12 +0000327int
328PyObject_Print(PyObject *op, FILE *fp, int flags)
329{
330 return internal_print(op, fp, flags, 0);
331}
332
Guido van Rossum38938152006-08-21 23:36:26 +0000333/* For debugging convenience. Set a breakpoint here and call it from your DLL */
334void
Thomas Woutersb2137042007-02-01 18:02:27 +0000335_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000336{
337}
338
Neal Norwitz1a997502003-01-13 20:13:12 +0000339
Barry Warsaw9bf16442001-01-23 16:24:35 +0000340/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000341void
342_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000343{
Barry Warsaweefb1072001-02-22 22:39:18 +0000344 if (op == NULL)
345 fprintf(stderr, "NULL\n");
346 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000347 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000348 (void)PyObject_Print(op, stderr, 0);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000349 /* XXX(twouters) cast refcount to long until %zd is
350 universally available */
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000351 fprintf(stderr, "\n"
352 "type : %s\n"
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000353 "refcount: %ld\n"
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000354 "address : %p\n",
Christian Heimes90aa7642007-12-19 02:45:37 +0000355 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000356 (long)op->ob_refcnt,
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000357 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000358 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000359}
Barry Warsaw903138f2001-01-23 16:33:18 +0000360
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000362PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363{
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000364 PyObject *res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000366 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000367#ifdef USE_STACKCHECK
368 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000369 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000370 return NULL;
371 }
372#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000373 if (v == NULL)
Walter Dörwald1ab83302007-05-18 17:15:44 +0000374 return PyUnicode_FromString("<NULL>");
Christian Heimes90aa7642007-12-19 02:45:37 +0000375 if (Py_TYPE(v)->tp_repr == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000376 return PyUnicode_FromFormat("<%s object at %p>",
377 v->ob_type->tp_name, v);
378 res = (*v->ob_type->tp_repr)(v);
379 if (res != NULL && !PyUnicode_Check(res)) {
380 PyErr_Format(PyExc_TypeError,
381 "__repr__ returned non-string (type %.200s)",
382 res->ob_type->tp_name);
383 Py_DECREF(res);
384 return NULL;
385 }
386 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387}
388
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000389PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000390PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000391{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000392 PyObject *res;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000393 if (PyErr_CheckSignals())
394 return NULL;
395#ifdef USE_STACKCHECK
396 if (PyOS_CheckStack()) {
397 PyErr_SetString(PyExc_MemoryError, "stack overflow");
398 return NULL;
399 }
400#endif
Guido van Rossumc6004111993-11-05 10:22:19 +0000401 if (v == NULL)
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000402 return PyUnicode_FromString("<NULL>");
Neil Schemenauercf52c072005-08-12 17:34:58 +0000403 if (PyUnicode_CheckExact(v)) {
404 Py_INCREF(v);
405 return v;
406 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000407 if (Py_TYPE(v)->tp_str == NULL)
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000408 return PyObject_Repr(v);
409
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000410 /* It is possible for a type to have a tp_str representation that loops
411 infinitely. */
412 if (Py_EnterRecursiveCall(" while getting the str of an object"))
413 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +0000414 res = (*Py_TYPE(v)->tp_str)(v);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000415 Py_LeaveRecursiveCall();
Guido van Rossum4c08d552000-03-10 22:55:18 +0000416 if (res == NULL)
417 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000418 if (!PyUnicode_Check(res)) {
Neil Schemenauercf52c072005-08-12 17:34:58 +0000419 PyErr_Format(PyExc_TypeError,
420 "__str__ returned non-string (type %.200s)",
Christian Heimes90aa7642007-12-19 02:45:37 +0000421 Py_TYPE(res)->tp_name);
Neil Schemenauercf52c072005-08-12 17:34:58 +0000422 Py_DECREF(res);
423 return NULL;
424 }
425 return res;
426}
427
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000428
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000429/* The new comparison philosophy is: we completely separate three-way
430 comparison from rich comparison. That is, PyObject_Compare() and
431 PyObject_Cmp() *just* use the tp_compare slot. And PyObject_RichCompare()
432 and PyObject_RichCompareBool() *just* use the tp_richcompare slot.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000433
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000434 See (*) below for practical amendments.
435
436 IOW, only cmp() uses tp_compare; the comparison operators (==, !=, <=, <,
437 >=, >) only use tp_richcompare. Note that list.sort() only uses <.
438
439 (And yes, eventually we'll rip out cmp() and tp_compare.)
440
441 The calling conventions are different: tp_compare only gets called with two
442 objects of the appropriate type; tp_richcompare gets called with a first
443 argument of the appropriate type and a second object of an arbitrary type.
444 We never do any kind of coercion.
445
446 The return conventions are also different.
447
448 The tp_compare slot should return a C int, as follows:
449
450 -1 if a < b or if an exception occurred
451 0 if a == b
452 +1 if a > b
453
454 No other return values are allowed. PyObject_Compare() has the same
455 calling convention.
456
457 The tp_richcompare slot should return an object, as follows:
458
459 NULL if an exception occurred
460 NotImplemented if the requested comparison is not implemented
461 any other false value if the requested comparison is false
462 any other true value if the requested comparison is true
463
464 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
465 NotImplemented.
466
467 (*) Practical amendments:
468
469 - If rich comparison returns NotImplemented, == and != are decided by
470 comparing the object pointer (i.e. falling back to the base object
471 implementation).
472
473 - If three-way comparison is not implemented, it falls back on rich
474 comparison (but not the other way around!).
475
Guido van Rossuma4073002002-05-31 20:03:54 +0000476*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000477
478/* Forward */
479static PyObject *do_richcompare(PyObject *v, PyObject *w, int op);
480
481/* Perform a three-way comparison, raising TypeError if three-way comparison
482 is not supported. */
Guido van Rossuma4073002002-05-31 20:03:54 +0000483static int
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000484do_compare(PyObject *v, PyObject *w)
Guido van Rossuma4073002002-05-31 20:03:54 +0000485{
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000486 cmpfunc f;
487 int ok;
488
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489 if (v->ob_type == w->ob_type &&
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000490 (f = v->ob_type->tp_compare) != NULL) {
491 return (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000492 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000493
494 /* Now try three-way compare before giving up. This is intentionally
495 elaborate; if you have a it will raise TypeError if it detects two
496 objects that aren't ordered with respect to each other. */
497 ok = PyObject_RichCompareBool(v, w, Py_LT);
498 if (ok < 0)
499 return -1; /* Error */
500 if (ok)
501 return -1; /* Less than */
502 ok = PyObject_RichCompareBool(v, w, Py_GT);
503 if (ok < 0)
504 return -1; /* Error */
505 if (ok)
506 return 1; /* Greater than */
507 ok = PyObject_RichCompareBool(v, w, Py_EQ);
508 if (ok < 0)
509 return -1; /* Error */
510 if (ok)
511 return 0; /* Equal */
512
513 /* Give up */
514 PyErr_Format(PyExc_TypeError,
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000515 "unorderable types: '%.100s' != '%.100s'",
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000516 v->ob_type->tp_name,
517 w->ob_type->tp_name);
518 return -1;
Guido van Rossuma4073002002-05-31 20:03:54 +0000519}
520
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000521/* Perform a three-way comparison. This wraps do_compare() with a check for
522 NULL arguments and a recursion check. */
523int
524PyObject_Compare(PyObject *v, PyObject *w)
525{
526 int res;
Guido van Rossuma4073002002-05-31 20:03:54 +0000527
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000528 if (v == NULL || w == NULL) {
529 if (!PyErr_Occurred())
530 PyErr_BadInternalCall();
531 return -1;
532 }
533 if (Py_EnterRecursiveCall(" in cmp"))
534 return -1;
535 res = do_compare(v, w);
536 Py_LeaveRecursiveCall();
537 return res < 0 ? -1 : res;
538}
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000539
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000540/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000541int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000542
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000543static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000544
545/* Perform a rich comparison, raising TypeError when the requested comparison
546 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000547static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000548do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000549{
550 richcmpfunc f;
551 PyObject *res;
552
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000553 if (v->ob_type != w->ob_type &&
554 PyType_IsSubtype(w->ob_type, v->ob_type) &&
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000555 (f = w->ob_type->tp_richcompare) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000556 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000557 if (res != Py_NotImplemented)
558 return res;
559 Py_DECREF(res);
560 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000561 if ((f = v->ob_type->tp_richcompare) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000562 res = (*f)(v, w, op);
563 if (res != Py_NotImplemented)
564 return res;
565 Py_DECREF(res);
566 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000567 if ((f = w->ob_type->tp_richcompare) != NULL) {
568 res = (*f)(w, v, _Py_SwappedOp[op]);
569 if (res != Py_NotImplemented)
570 return res;
571 Py_DECREF(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000572 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000573 /* If neither object implements it, provide a sensible default
574 for == and !=, but raise an exception for ordering. */
575 switch (op) {
576 case Py_EQ:
577 res = (v == w) ? Py_True : Py_False;
578 break;
579 case Py_NE:
580 res = (v != w) ? Py_True : Py_False;
581 break;
582 default:
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000583 /* XXX Special-case None so it doesn't show as NoneType() */
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000584 PyErr_Format(PyExc_TypeError,
585 "unorderable types: %.100s() %s %.100s()",
586 v->ob_type->tp_name,
587 opstrings[op],
588 w->ob_type->tp_name);
589 return NULL;
590 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000591 Py_INCREF(res);
592 return res;
593}
594
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000595/* Perform a rich comparison with object result. This wraps do_richcompare()
596 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000597
Guido van Rossume797ec12001-01-17 15:24:28 +0000598PyObject *
599PyObject_RichCompare(PyObject *v, PyObject *w, int op)
600{
601 PyObject *res;
602
603 assert(Py_LT <= op && op <= Py_GE);
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000604 if (v == NULL || w == NULL) {
605 if (!PyErr_Occurred())
606 PyErr_BadInternalCall();
607 return NULL;
608 }
Armin Rigo2b3eb402003-10-28 12:05:48 +0000609 if (Py_EnterRecursiveCall(" in cmp"))
610 return NULL;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000611 res = do_richcompare(v, w, op);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000612 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000613 return res;
614}
615
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000616/* Perform a rich comparison with integer result. This wraps
617 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000618int
619PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
620{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000621 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000622 int ok;
623
Raymond Hettinger93d44812004-03-21 17:01:44 +0000624 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000625 if (res == NULL)
626 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000627 if (PyBool_Check(res))
628 ok = (res == Py_True);
629 else
630 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000631 Py_DECREF(res);
632 return ok;
633}
Fred Drake13634cf2000-06-29 19:17:04 +0000634
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000635/* Turn the result of a three-way comparison into the result expected by a
636 rich comparison. */
637PyObject *
638Py_CmpToRich(int op, int cmp)
639{
640 PyObject *res;
641 int ok;
642
643 if (PyErr_Occurred())
644 return NULL;
645 switch (op) {
646 case Py_LT:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000647 ok = cmp < 0;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000648 break;
649 case Py_LE:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000650 ok = cmp <= 0;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000651 break;
652 case Py_EQ:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000653 ok = cmp == 0;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000654 break;
655 case Py_NE:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000656 ok = cmp != 0;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000657 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000658 case Py_GT:
659 ok = cmp > 0;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000660 break;
661 case Py_GE:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000662 ok = cmp >= 0;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000663 break;
664 default:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000665 PyErr_BadArgument();
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000666 return NULL;
667 }
668 res = ok ? Py_True : Py_False;
669 Py_INCREF(res);
670 return res;
671}
672
Fred Drake13634cf2000-06-29 19:17:04 +0000673/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000674 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000675
676 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
677*/
678
679long
Fred Drake100814d2000-07-09 15:48:49 +0000680_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000681{
Tim Peters39dce292000-08-15 03:34:48 +0000682 double intpart, fractpart;
683 int expo;
684 long hipart;
685 long x; /* the final hash value */
686 /* This is designed so that Python numbers of different types
687 * that compare equal hash to the same value; otherwise comparisons
688 * of mapping keys will turn out weird.
689 */
690
Tim Peters39dce292000-08-15 03:34:48 +0000691 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000692 if (fractpart == 0.0) {
693 /* This must return the same hash as an equal int or long. */
694 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
695 /* Convert to long and use its hash. */
696 PyObject *plong; /* converted to Python long */
697 if (Py_IS_INFINITY(intpart))
698 /* can't convert to long int -- arbitrary */
699 v = v < 0 ? -271828.0 : 314159.0;
700 plong = PyLong_FromDouble(v);
701 if (plong == NULL)
702 return -1;
703 x = PyObject_Hash(plong);
704 Py_DECREF(plong);
705 return x;
706 }
707 /* Fits in a C long == a Python int, so is its own hash. */
708 x = (long)intpart;
709 if (x == -1)
710 x = -2;
711 return x;
712 }
713 /* The fractional part is non-zero, so we don't have to worry about
714 * making this match the hash of some other type.
715 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000716 * Since the VAX D double format has 56 mantissa bits, which is the
717 * most of any double format in use, each of these parts may have as
718 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000719 * So, assuming sizeof(long) >= 4, each part can be broken into two
720 * longs; frexp and multiplication are used to do that.
721 * Also, since the Cray double format has 15 exponent bits, which is
722 * the most of any double format in use, shifting the exponent field
723 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000724 */
Tim Peters39dce292000-08-15 03:34:48 +0000725 v = frexp(v, &expo);
726 v *= 2147483648.0; /* 2**31 */
727 hipart = (long)v; /* take the top 32 bits */
728 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
729 x = hipart + (long)v + (expo << 15);
730 if (x == -1)
731 x = -2;
732 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000733}
734
735long
Fred Drake100814d2000-07-09 15:48:49 +0000736_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000737{
738#if SIZEOF_LONG >= SIZEOF_VOID_P
739 return (long)p;
740#else
741 /* convert to a Python long and hash that */
742 PyObject* longobj;
743 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000744
Fred Drake13634cf2000-06-29 19:17:04 +0000745 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
746 x = -1;
747 goto finally;
748 }
749 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000750
Fred Drake13634cf2000-06-29 19:17:04 +0000751finally:
752 Py_XDECREF(longobj);
753 return x;
754#endif
755}
756
757
Guido van Rossum9bfef441993-03-29 10:43:31 +0000758long
Fred Drake100814d2000-07-09 15:48:49 +0000759PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000760{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000762 if (tp->tp_hash != NULL)
763 return (*tp->tp_hash)(v);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000764 /* Otherwise, the object can't be hashed */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000765 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
766 v->ob_type->tp_name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000767 return -1;
768}
769
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000770PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000771PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000772{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000773 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000774
Christian Heimes90aa7642007-12-19 02:45:37 +0000775 if (Py_TYPE(v)->tp_getattr != NULL)
776 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000777 w = PyUnicode_InternFromString(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 if (w == NULL)
779 return NULL;
780 res = PyObject_GetAttr(v, w);
781 Py_XDECREF(w);
782 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000783}
784
785int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000786PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000787{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000788 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000789 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000790 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000791 return 1;
792 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000793 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000794 return 0;
795}
796
797int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000798PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000799{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000800 PyObject *s;
801 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000802
Christian Heimes90aa7642007-12-19 02:45:37 +0000803 if (Py_TYPE(v)->tp_setattr != NULL)
804 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000805 s = PyUnicode_InternFromString(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000806 if (s == NULL)
807 return -1;
808 res = PyObject_SetAttr(v, s, w);
809 Py_XDECREF(s);
810 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000811}
812
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000813PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000814PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000815{
Christian Heimes90aa7642007-12-19 02:45:37 +0000816 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000817
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000818 if (!PyUnicode_Check(name)) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000819 PyErr_Format(PyExc_TypeError,
820 "attribute name must be string, not '%.200s'",
821 name->ob_type->tp_name);
822 return NULL;
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000823 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000824 if (tp->tp_getattro != NULL)
825 return (*tp->tp_getattro)(v, name);
826 if (tp->tp_getattr != NULL)
Martin v. Löwis5b222132007-06-10 09:51:05 +0000827 return (*tp->tp_getattr)(v, PyUnicode_AsString(name));
Tim Peters6d6c1a32001-08-02 04:15:00 +0000828 PyErr_Format(PyExc_AttributeError,
Walter Dörwaldd376dd92007-06-11 15:37:20 +0000829 "'%.50s' object has no attribute '%U'",
830 tp->tp_name, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000832}
833
834int
Fred Drake100814d2000-07-09 15:48:49 +0000835PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000836{
837 PyObject *res = PyObject_GetAttr(v, name);
838 if (res != NULL) {
839 Py_DECREF(res);
840 return 1;
841 }
842 PyErr_Clear();
843 return 0;
844}
845
846int
Fred Drake100814d2000-07-09 15:48:49 +0000847PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000848{
Christian Heimes90aa7642007-12-19 02:45:37 +0000849 PyTypeObject *tp = Py_TYPE(v);
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000850 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000851
Martin v. Löwis5b222132007-06-10 09:51:05 +0000852 if (!PyUnicode_Check(name)) {
853 PyErr_Format(PyExc_TypeError,
854 "attribute name must be string, not '%.200s'",
855 name->ob_type->tp_name);
856 return -1;
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000857 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000858 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000859
Martin v. Löwis5b222132007-06-10 09:51:05 +0000860 PyUnicode_InternInPlace(&name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000861 if (tp->tp_setattro != NULL) {
862 err = (*tp->tp_setattro)(v, name, value);
863 Py_DECREF(name);
864 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000865 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 if (tp->tp_setattr != NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000867 err = (*tp->tp_setattr)(v, PyUnicode_AsString(name), value);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 Py_DECREF(name);
869 return err;
870 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000871 Py_DECREF(name);
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000872 assert(name->ob_refcnt >= 1);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000873 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
874 PyErr_Format(PyExc_TypeError,
875 "'%.100s' object has no attributes "
Walter Dörwaldd376dd92007-06-11 15:37:20 +0000876 "(%s .%U)",
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877 tp->tp_name,
878 value==NULL ? "del" : "assign to",
Walter Dörwaldd376dd92007-06-11 15:37:20 +0000879 name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000880 else
881 PyErr_Format(PyExc_TypeError,
882 "'%.100s' object has only read-only attributes "
Walter Dörwaldd376dd92007-06-11 15:37:20 +0000883 "(%s .%U)",
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884 tp->tp_name,
885 value==NULL ? "del" : "assign to",
Walter Dörwaldd376dd92007-06-11 15:37:20 +0000886 name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887 return -1;
888}
889
890/* Helper to get a pointer to an object's __dict__ slot, if any */
891
892PyObject **
893_PyObject_GetDictPtr(PyObject *obj)
894{
Martin v. Löwis725507b2006-03-07 12:08:51 +0000895 Py_ssize_t dictoffset;
Christian Heimes90aa7642007-12-19 02:45:37 +0000896 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000897
Tim Peters6d6c1a32001-08-02 04:15:00 +0000898 dictoffset = tp->tp_dictoffset;
899 if (dictoffset == 0)
900 return NULL;
901 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000902 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000903 size_t size;
904
905 tsize = ((PyVarObject *)obj)->ob_size;
906 if (tsize < 0)
907 tsize = -tsize;
908 size = _PyObject_VAR_SIZE(tp, tsize);
909
Tim Peters6d483d32001-10-06 21:27:34 +0000910 dictoffset += (long)size;
911 assert(dictoffset > 0);
912 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000913 }
914 return (PyObject **) ((char *)obj + dictoffset);
915}
916
Tim Peters6d6c1a32001-08-02 04:15:00 +0000917PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +0000918PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +0000919{
920 Py_INCREF(obj);
921 return obj;
922}
923
Michael W. Hudson1593f502004-09-14 17:09:47 +0000924/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
925
Raymond Hettinger01538262003-03-17 08:24:35 +0000926PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000927PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
928{
Christian Heimes90aa7642007-12-19 02:45:37 +0000929 PyTypeObject *tp = Py_TYPE(obj);
Guido van Rossum056fbf42002-08-19 19:22:50 +0000930 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000931 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +0000933 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000934 PyObject **dictptr;
935
Martin v. Löwis5b222132007-06-10 09:51:05 +0000936 if (!PyUnicode_Check(name)){
937 PyErr_Format(PyExc_TypeError,
938 "attribute name must be string, not '%.200s'",
939 name->ob_type->tp_name);
940 return NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000941 }
942 else
943 Py_INCREF(name);
944
Tim Peters6d6c1a32001-08-02 04:15:00 +0000945 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000946 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000947 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000948 }
949
Christian Heimesa62da1d2008-01-12 19:39:10 +0000950#if 0 /* XXX this is not quite _PyType_Lookup anymore */
Guido van Rossum056fbf42002-08-19 19:22:50 +0000951 /* Inline _PyType_Lookup */
952 {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000953 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +0000954 PyObject *mro, *base, *dict;
955
956 /* Look in tp_dict of types in MRO */
957 mro = tp->tp_mro;
958 assert(mro != NULL);
959 assert(PyTuple_Check(mro));
960 n = PyTuple_GET_SIZE(mro);
961 for (i = 0; i < n; i++) {
962 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000963 assert(PyType_Check(base));
964 dict = ((PyTypeObject *)base)->tp_dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +0000965 assert(dict && PyDict_Check(dict));
966 descr = PyDict_GetItem(dict, name);
967 if (descr != NULL)
968 break;
969 }
970 }
Christian Heimesa62da1d2008-01-12 19:39:10 +0000971#else
972 descr = _PyType_Lookup(tp, name);
973#endif
Guido van Rossum056fbf42002-08-19 19:22:50 +0000974
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +0000975 Py_XINCREF(descr);
976
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000978 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000979 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000980 if (f != NULL && PyDescr_IsData(descr)) {
981 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +0000982 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000983 goto done;
984 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 }
986
Guido van Rossumc66ff442002-08-19 16:50:48 +0000987 /* Inline _PyObject_GetDictPtr */
988 dictoffset = tp->tp_dictoffset;
989 if (dictoffset != 0) {
990 PyObject *dict;
991 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000992 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +0000993 size_t size;
994
995 tsize = ((PyVarObject *)obj)->ob_size;
996 if (tsize < 0)
997 tsize = -tsize;
998 size = _PyObject_VAR_SIZE(tp, tsize);
999
1000 dictoffset += (long)size;
1001 assert(dictoffset > 0);
1002 assert(dictoffset % SIZEOF_VOID_P == 0);
1003 }
1004 dictptr = (PyObject **) ((char *)obj + dictoffset);
1005 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 if (dict != NULL) {
Christian Heimes969fe572008-01-25 11:23:10 +00001007 Py_INCREF(dict);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001008 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001009 if (res != NULL) {
1010 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001011 Py_XDECREF(descr);
Christian Heimes969fe572008-01-25 11:23:10 +00001012 Py_DECREF(dict);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001013 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 }
Christian Heimes969fe572008-01-25 11:23:10 +00001015 Py_DECREF(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001016 }
1017 }
1018
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001019 if (f != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001020 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001021 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001022 goto done;
1023 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024
1025 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001026 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001027 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001028 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029 }
1030
1031 PyErr_Format(PyExc_AttributeError,
1032 "'%.50s' object has no attribute '%.400s'",
Martin v. Löwis5b222132007-06-10 09:51:05 +00001033 tp->tp_name, PyUnicode_AsString(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001034 done:
1035 Py_DECREF(name);
1036 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037}
1038
1039int
1040PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1041{
Christian Heimes90aa7642007-12-19 02:45:37 +00001042 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043 PyObject *descr;
1044 descrsetfunc f;
1045 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001046 int res = -1;
1047
Martin v. Löwis5b222132007-06-10 09:51:05 +00001048 if (!PyUnicode_Check(name)){
1049 PyErr_Format(PyExc_TypeError,
1050 "attribute name must be string, not '%.200s'",
1051 name->ob_type->tp_name);
1052 return -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001053 }
1054 else
1055 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056
1057 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001058 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001059 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001060 }
1061
1062 descr = _PyType_Lookup(tp, name);
1063 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001064 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001065 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001066 if (f != NULL && PyDescr_IsData(descr)) {
1067 res = f(descr, obj, value);
1068 goto done;
1069 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070 }
1071
1072 dictptr = _PyObject_GetDictPtr(obj);
1073 if (dictptr != NULL) {
1074 PyObject *dict = *dictptr;
1075 if (dict == NULL && value != NULL) {
1076 dict = PyDict_New();
1077 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001078 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079 *dictptr = dict;
1080 }
1081 if (dict != NULL) {
Christian Heimes969fe572008-01-25 11:23:10 +00001082 Py_INCREF(dict);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 if (value == NULL)
1084 res = PyDict_DelItem(dict, name);
1085 else
1086 res = PyDict_SetItem(dict, name, value);
1087 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1088 PyErr_SetObject(PyExc_AttributeError, name);
Christian Heimes969fe572008-01-25 11:23:10 +00001089 Py_DECREF(dict);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001090 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 }
1092 }
1093
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001094 if (f != NULL) {
1095 res = f(descr, obj, value);
1096 goto done;
1097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098
1099 if (descr == NULL) {
1100 PyErr_Format(PyExc_AttributeError,
Walter Dörwaldd376dd92007-06-11 15:37:20 +00001101 "'%.100s' object has no attribute '%U'",
1102 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001103 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001104 }
1105
1106 PyErr_Format(PyExc_AttributeError,
Walter Dörwaldd376dd92007-06-11 15:37:20 +00001107 "'%.50s' object attribute '%U' is read-only",
1108 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001109 done:
1110 Py_DECREF(name);
1111 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001112}
1113
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001114/* Test a value used as condition, e.g., in a for or if statement.
1115 Return -1 if an error occurred */
1116
1117int
Fred Drake100814d2000-07-09 15:48:49 +00001118PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001119{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001120 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001121 if (v == Py_True)
1122 return 1;
1123 if (v == Py_False)
1124 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001125 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001126 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001127 else if (v->ob_type->tp_as_number != NULL &&
Jack Diederich4dafcc42006-11-28 19:15:13 +00001128 v->ob_type->tp_as_number->nb_bool != NULL)
1129 res = (*v->ob_type->tp_as_number->nb_bool)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001130 else if (v->ob_type->tp_as_mapping != NULL &&
1131 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001132 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001133 else if (v->ob_type->tp_as_sequence != NULL &&
1134 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001135 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1136 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001137 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001138 /* if it is negative, it should be either -1 or -2 */
1139 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001140}
1141
Tim Peters803526b2002-07-07 05:13:56 +00001142/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001143 Return -1 if an error occurred */
1144
1145int
Fred Drake100814d2000-07-09 15:48:49 +00001146PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001147{
1148 int res;
1149 res = PyObject_IsTrue(v);
1150 if (res < 0)
1151 return res;
1152 return res == 0;
1153}
1154
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001155/* Test whether an object can be called */
1156
1157int
Fred Drake100814d2000-07-09 15:48:49 +00001158PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001159{
1160 if (x == NULL)
1161 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001162 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001163}
1164
Georg Brandle32b4222007-03-10 22:13:27 +00001165/* ------------------------- PyObject_Dir() helpers ------------------------- */
1166
Tim Peters7eea37e2001-09-04 22:08:56 +00001167/* Helper for PyObject_Dir.
1168 Merge the __dict__ of aclass into dict, and recursively also all
1169 the __dict__s of aclass's base classes. The order of merging isn't
1170 defined, as it's expected that only the final set of dict keys is
1171 interesting.
1172 Return 0 on success, -1 on error.
1173*/
1174
1175static int
1176merge_class_dict(PyObject* dict, PyObject* aclass)
1177{
1178 PyObject *classdict;
1179 PyObject *bases;
1180
1181 assert(PyDict_Check(dict));
1182 assert(aclass);
1183
1184 /* Merge in the type's dict (if any). */
1185 classdict = PyObject_GetAttrString(aclass, "__dict__");
1186 if (classdict == NULL)
1187 PyErr_Clear();
1188 else {
1189 int status = PyDict_Update(dict, classdict);
1190 Py_DECREF(classdict);
1191 if (status < 0)
1192 return -1;
1193 }
1194
1195 /* Recursively merge in the base types' (if any) dicts. */
1196 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001197 if (bases == NULL)
1198 PyErr_Clear();
1199 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001200 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001201 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001202 n = PySequence_Size(bases); /* This better be right */
1203 if (n < 0)
1204 PyErr_Clear();
1205 else {
1206 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001207 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001208 PyObject *base = PySequence_GetItem(bases, i);
1209 if (base == NULL) {
1210 Py_DECREF(bases);
1211 return -1;
1212 }
Tim Peters18e70832003-02-05 19:35:19 +00001213 status = merge_class_dict(dict, base);
1214 Py_DECREF(base);
1215 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001216 Py_DECREF(bases);
1217 return -1;
1218 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001219 }
1220 }
1221 Py_DECREF(bases);
1222 }
1223 return 0;
1224}
1225
Georg Brandle32b4222007-03-10 22:13:27 +00001226/* Helper for PyObject_Dir without arguments: returns the local scope. */
1227static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001228_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001229{
Georg Brandled3b8382007-03-12 13:15:14 +00001230 PyObject *names;
Georg Brandle32b4222007-03-10 22:13:27 +00001231 PyObject *locals = PyEval_GetLocals();
Tim Peters305b5852001-09-17 02:38:46 +00001232
Georg Brandle32b4222007-03-10 22:13:27 +00001233 if (locals == NULL) {
1234 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1235 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001236 }
1237
Georg Brandled3b8382007-03-12 13:15:14 +00001238 names = PyMapping_Keys(locals);
1239 if (!names)
1240 return NULL;
1241 if (!PyList_Check(names)) {
1242 PyErr_Format(PyExc_TypeError,
1243 "dir(): expected keys() of locals to be a list, "
Christian Heimes90aa7642007-12-19 02:45:37 +00001244 "not '%.200s'", Py_TYPE(names)->tp_name);
Georg Brandled3b8382007-03-12 13:15:14 +00001245 Py_DECREF(names);
1246 return NULL;
1247 }
Georg Brandle32b4222007-03-10 22:13:27 +00001248 /* the locals don't need to be DECREF'd */
Georg Brandled3b8382007-03-12 13:15:14 +00001249 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001250}
1251
1252/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
Guido van Rossum98297ee2007-11-06 21:34:58 +00001253 We deliberately don't suck up its __class__, as methods belonging to the
1254 metaclass would probably be more confusing than helpful.
Georg Brandle32b4222007-03-10 22:13:27 +00001255*/
Guido van Rossum98297ee2007-11-06 21:34:58 +00001256static PyObject *
Georg Brandle32b4222007-03-10 22:13:27 +00001257_specialized_dir_type(PyObject *obj)
1258{
1259 PyObject *result = NULL;
1260 PyObject *dict = PyDict_New();
1261
1262 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1263 result = PyDict_Keys(dict);
1264
1265 Py_XDECREF(dict);
Tim Peters305b5852001-09-17 02:38:46 +00001266 return result;
1267}
1268
Georg Brandle32b4222007-03-10 22:13:27 +00001269/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1270static PyObject *
1271_specialized_dir_module(PyObject *obj)
Tim Peters7eea37e2001-09-04 22:08:56 +00001272{
Georg Brandle32b4222007-03-10 22:13:27 +00001273 PyObject *result = NULL;
1274 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Tim Peters7eea37e2001-09-04 22:08:56 +00001275
Georg Brandle32b4222007-03-10 22:13:27 +00001276 if (dict != NULL) {
1277 if (PyDict_Check(dict))
1278 result = PyDict_Keys(dict);
1279 else {
1280 PyErr_Format(PyExc_TypeError,
1281 "%.200s.__dict__ is not a dictionary",
1282 PyModule_GetName(obj));
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001283 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001284 }
1285
Georg Brandle32b4222007-03-10 22:13:27 +00001286 Py_XDECREF(dict);
1287 return result;
1288}
Tim Peters7eea37e2001-09-04 22:08:56 +00001289
Georg Brandle32b4222007-03-10 22:13:27 +00001290/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1291 and recursively up the __class__.__bases__ chain.
1292*/
1293static PyObject *
1294_generic_dir(PyObject *obj)
1295{
1296 PyObject *result = NULL;
1297 PyObject *dict = NULL;
1298 PyObject *itsclass = NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001299
Georg Brandle32b4222007-03-10 22:13:27 +00001300 /* Get __dict__ (which may or may not be a real dict...) */
1301 dict = PyObject_GetAttrString(obj, "__dict__");
1302 if (dict == NULL) {
1303 PyErr_Clear();
1304 dict = PyDict_New();
1305 }
1306 else if (!PyDict_Check(dict)) {
1307 Py_DECREF(dict);
1308 dict = PyDict_New();
1309 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001310 else {
Georg Brandle32b4222007-03-10 22:13:27 +00001311 /* Copy __dict__ to avoid mutating it. */
1312 PyObject *temp = PyDict_Copy(dict);
1313 Py_DECREF(dict);
1314 dict = temp;
Tim Peters7eea37e2001-09-04 22:08:56 +00001315 }
1316
Georg Brandle32b4222007-03-10 22:13:27 +00001317 if (dict == NULL)
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001318 goto error;
Tim Peters7eea37e2001-09-04 22:08:56 +00001319
Georg Brandle32b4222007-03-10 22:13:27 +00001320 /* Merge in attrs reachable from its class. */
1321 itsclass = PyObject_GetAttrString(obj, "__class__");
1322 if (itsclass == NULL)
1323 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1324 __class__ exists? */
1325 PyErr_Clear();
1326 else {
1327 if (merge_class_dict(dict, itsclass) != 0)
1328 goto error;
1329 }
1330
1331 result = PyDict_Keys(dict);
Tim Peters7eea37e2001-09-04 22:08:56 +00001332 /* fall through */
Georg Brandle32b4222007-03-10 22:13:27 +00001333error:
1334 Py_XDECREF(itsclass);
1335 Py_XDECREF(dict);
1336 return result;
1337}
1338
1339/* Helper for PyObject_Dir: object introspection.
1340 This calls one of the above specialized versions if no __dir__ method
1341 exists. */
1342static PyObject *
1343_dir_object(PyObject *obj)
1344{
1345 PyObject * result = NULL;
1346 PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type,
1347 "__dir__");
1348
1349 assert(obj);
1350 if (dirfunc == NULL) {
1351 /* use default implementation */
1352 PyErr_Clear();
1353 if (PyModule_Check(obj))
1354 result = _specialized_dir_module(obj);
1355 else if (PyType_Check(obj))
1356 result = _specialized_dir_type(obj);
1357 else
1358 result = _generic_dir(obj);
1359 }
1360 else {
1361 /* use __dir__ */
1362 result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
1363 Py_DECREF(dirfunc);
1364 if (result == NULL)
1365 return NULL;
1366
1367 /* result must be a list */
1368 /* XXX(gbrandl): could also check if all items are strings */
1369 if (!PyList_Check(result)) {
1370 PyErr_Format(PyExc_TypeError,
1371 "__dir__() must return a list, not %.200s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001372 Py_TYPE(result)->tp_name);
Georg Brandle32b4222007-03-10 22:13:27 +00001373 Py_DECREF(result);
1374 result = NULL;
1375 }
1376 }
1377
1378 return result;
1379}
1380
1381/* Implementation of dir() -- if obj is NULL, returns the names in the current
1382 (local) scope. Otherwise, performs introspection of the object: returns a
1383 sorted list of attribute names (supposedly) accessible from the object
1384*/
1385PyObject *
1386PyObject_Dir(PyObject *obj)
1387{
1388 PyObject * result;
1389
1390 if (obj == NULL)
1391 /* no object -- introspect the locals */
1392 result = _dir_locals();
1393 else
1394 /* object -- introspect the object */
1395 result = _dir_object(obj);
1396
1397 assert(result == NULL || PyList_Check(result));
1398
1399 if (result != NULL && PyList_Sort(result) != 0) {
1400 /* sorting the list failed */
1401 Py_DECREF(result);
1402 result = NULL;
1403 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001404
Tim Peters7eea37e2001-09-04 22:08:56 +00001405 return result;
1406}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001407
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001408/*
1409NoObject is usable as a non-NULL undefined value, used by the macro None.
1410There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001411so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001412(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001413*/
1414
Guido van Rossum0c182a11992-03-27 17:26:13 +00001415/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001416static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001417none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001418{
Walter Dörwald1ab83302007-05-18 17:15:44 +00001419 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001420}
1421
Barry Warsaw9bf16442001-01-23 16:24:35 +00001422/* ARGUSED */
1423static void
Tim Peters803526b2002-07-07 05:13:56 +00001424none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001425{
1426 /* This should never get called, but we also don't want to SEGV if
1427 * we accidently decref None out of existance.
1428 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001429 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001430}
1431
1432
Guido van Rossumba21a492001-08-16 08:17:26 +00001433static PyTypeObject PyNone_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001434 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumba21a492001-08-16 08:17:26 +00001435 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001436 0,
1437 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001438 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001439 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001440 0, /*tp_getattr*/
1441 0, /*tp_setattr*/
1442 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001443 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001444 0, /*tp_as_number*/
1445 0, /*tp_as_sequence*/
1446 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001447 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001448};
1449
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001450PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001451 _PyObject_EXTRA_INIT
1452 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001453};
1454
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001455/* NotImplemented is an object that can be used to signal that an
1456 operation is not implemented for the given type combination. */
1457
1458static PyObject *
1459NotImplemented_repr(PyObject *op)
1460{
Walter Dörwald1ab83302007-05-18 17:15:44 +00001461 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001462}
1463
1464static PyTypeObject PyNotImplemented_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001465 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumba21a492001-08-16 08:17:26 +00001466 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001467 0,
1468 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001469 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001470 0, /*tp_print*/
1471 0, /*tp_getattr*/
1472 0, /*tp_setattr*/
1473 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001474 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001475 0, /*tp_as_number*/
1476 0, /*tp_as_sequence*/
1477 0, /*tp_as_mapping*/
1478 0, /*tp_hash */
1479};
1480
1481PyObject _Py_NotImplementedStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001482 _PyObject_EXTRA_INIT
1483 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001484};
1485
Guido van Rossumba21a492001-08-16 08:17:26 +00001486void
1487_Py_ReadyTypes(void)
1488{
1489 if (PyType_Ready(&PyType_Type) < 0)
1490 Py_FatalError("Can't initialize 'type'");
1491
Fred Drake0a4dd392004-07-02 18:57:45 +00001492 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1493 Py_FatalError("Can't initialize 'weakref'");
1494
Guido van Rossum77f6a652002-04-03 22:41:51 +00001495 if (PyType_Ready(&PyBool_Type) < 0)
1496 Py_FatalError("Can't initialize 'bool'");
1497
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001498 if (PyType_Ready(&PyBytes_Type) < 0)
1499 Py_FatalError("Can't initialize 'bytes'");
1500
Guido van Rossumcacfc072002-05-24 19:01:59 +00001501 if (PyType_Ready(&PyString_Type) < 0)
1502 Py_FatalError("Can't initialize 'str'");
1503
Guido van Rossumba21a492001-08-16 08:17:26 +00001504 if (PyType_Ready(&PyList_Type) < 0)
1505 Py_FatalError("Can't initialize 'list'");
1506
1507 if (PyType_Ready(&PyNone_Type) < 0)
1508 Py_FatalError("Can't initialize type(None)");
1509
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001510 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1511 Py_FatalError("Can't initialize type(Ellipsis)");
1512
Guido van Rossumba21a492001-08-16 08:17:26 +00001513 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1514 Py_FatalError("Can't initialize type(NotImplemented)");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001515
1516 if (PyType_Ready(&PyCode_Type) < 0)
1517 Py_FatalError("Can't initialize 'code'");
Guido van Rossum826d8972007-10-30 18:34:07 +00001518
1519 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1520 Py_FatalError("Can't initialize StdPrinter");
Guido van Rossumba21a492001-08-16 08:17:26 +00001521}
1522
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001523
Guido van Rossum84a90321996-05-22 16:34:47 +00001524#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001525
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001526void
Fred Drake100814d2000-07-09 15:48:49 +00001527_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001528{
Tim Peters34592512002-07-11 06:23:50 +00001529 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001531 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001532 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001533}
1534
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001535void
Fred Drake100814d2000-07-09 15:48:49 +00001536_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001537{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001538#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001539 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001540#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001541 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001542 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001543 if (op == &refchain ||
Christian Heimesc8967002007-11-30 10:18:26 +00001544 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1545 fprintf(stderr, "* ob\n");
1546 _PyObject_Dump(op);
1547 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1548 _PyObject_Dump(op->_ob_prev->_ob_next);
1549 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1550 _PyObject_Dump(op->_ob_next->_ob_prev);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001551 Py_FatalError("UNREF invalid object");
Christian Heimesc8967002007-11-30 10:18:26 +00001552 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001553#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001554 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1555 if (p == op)
1556 break;
1557 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001558 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001559 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001560#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001561 op->_ob_next->_ob_prev = op->_ob_prev;
1562 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001563 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001564 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001565}
1566
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001567void
Fred Drake100814d2000-07-09 15:48:49 +00001568_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001569{
Christian Heimes90aa7642007-12-19 02:45:37 +00001570 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001571 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001572 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001573}
1574
Tim Peters269b2a62003-04-17 19:52:29 +00001575/* Print all live objects. Because PyObject_Print is called, the
1576 * interpreter must be in a healthy state.
1577 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001578void
Fred Drake100814d2000-07-09 15:48:49 +00001579_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001580{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001581 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001582 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001583 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001584 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001585 if (PyObject_Print(op, fp, 0) != 0)
1586 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001587 putc('\n', fp);
1588 }
1589}
1590
Tim Peters269b2a62003-04-17 19:52:29 +00001591/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1592 * doesn't make any calls to the Python C API, so is always safe to call.
1593 */
1594void
1595_Py_PrintReferenceAddresses(FILE *fp)
1596{
1597 PyObject *op;
1598 fprintf(fp, "Remaining object addresses:\n");
1599 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001600 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
Christian Heimes90aa7642007-12-19 02:45:37 +00001601 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001602}
1603
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001604PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001605_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001606{
1607 int i, n;
1608 PyObject *t = NULL;
1609 PyObject *res, *op;
1610
1611 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1612 return NULL;
1613 op = refchain._ob_next;
1614 res = PyList_New(0);
1615 if (res == NULL)
1616 return NULL;
1617 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1618 while (op == self || op == args || op == res || op == t ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001619 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001620 op = op->_ob_next;
1621 if (op == &refchain)
1622 return res;
1623 }
1624 if (PyList_Append(res, op) < 0) {
1625 Py_DECREF(res);
1626 return NULL;
1627 }
1628 op = op->_ob_next;
1629 }
1630 return res;
1631}
1632
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001633#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001634
1635
1636/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001637PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001638
1639
1640/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001641Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001642
1643
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001644/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001645
Thomas Wouters334fb892000-07-25 12:56:38 +00001646void *
Fred Drake100814d2000-07-09 15:48:49 +00001647PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001648{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001649 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001650}
1651
Thomas Wouters334fb892000-07-25 12:56:38 +00001652void *
1653PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001654{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001655 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001656}
1657
1658void
Thomas Wouters334fb892000-07-25 12:56:38 +00001659PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001660{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001661 PyMem_FREE(p);
1662}
1663
1664
Guido van Rossum86610361998-04-10 22:32:46 +00001665/* These methods are used to control infinite recursion in repr, str, print,
1666 etc. Container objects that may recursively contain themselves,
1667 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1668 Py_ReprLeave() to avoid infinite recursion.
1669
1670 Py_ReprEnter() returns 0 the first time it is called for a particular
1671 object and 1 every time thereafter. It returns -1 if an exception
1672 occurred. Py_ReprLeave() has no return value.
1673
1674 See dictobject.c and listobject.c for examples of use.
1675*/
1676
1677#define KEY "Py_Repr"
1678
1679int
Fred Drake100814d2000-07-09 15:48:49 +00001680Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001681{
1682 PyObject *dict;
1683 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001684 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001685
1686 dict = PyThreadState_GetDict();
1687 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001688 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001689 list = PyDict_GetItemString(dict, KEY);
1690 if (list == NULL) {
1691 list = PyList_New(0);
1692 if (list == NULL)
1693 return -1;
1694 if (PyDict_SetItemString(dict, KEY, list) < 0)
1695 return -1;
1696 Py_DECREF(list);
1697 }
1698 i = PyList_GET_SIZE(list);
1699 while (--i >= 0) {
1700 if (PyList_GET_ITEM(list, i) == obj)
1701 return 1;
1702 }
1703 PyList_Append(list, obj);
1704 return 0;
1705}
1706
1707void
Fred Drake100814d2000-07-09 15:48:49 +00001708Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001709{
1710 PyObject *dict;
1711 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001712 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001713
1714 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001715 if (dict == NULL)
1716 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001717 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001718 if (list == NULL || !PyList_Check(list))
1719 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001720 i = PyList_GET_SIZE(list);
1721 /* Count backwards because we always expect obj to be list[-1] */
1722 while (--i >= 0) {
1723 if (PyList_GET_ITEM(list, i) == obj) {
1724 PyList_SetSlice(list, i, i + 1, NULL);
1725 break;
1726 }
1727 }
1728}
Guido van Rossumd724b232000-03-13 16:01:29 +00001729
Tim Peters803526b2002-07-07 05:13:56 +00001730/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001731
Tim Peters803526b2002-07-07 05:13:56 +00001732/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001733int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001734
Tim Peters803526b2002-07-07 05:13:56 +00001735/* List of objects that still need to be cleaned up, singly linked via their
1736 * gc headers' gc_prev pointers.
1737 */
1738PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001739
Tim Peters803526b2002-07-07 05:13:56 +00001740/* Add op to the _PyTrash_delete_later list. Called when the current
1741 * call-stack depth gets large. op must be a currently untracked gc'ed
1742 * object, with refcount 0. Py_DECREF must already have been called on it.
1743 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001744void
Fred Drake100814d2000-07-09 15:48:49 +00001745_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001746{
Tim Peters803526b2002-07-07 05:13:56 +00001747 assert(PyObject_IS_GC(op));
1748 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1749 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00001750 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001751 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001752}
1753
Tim Peters803526b2002-07-07 05:13:56 +00001754/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1755 * the call-stack unwinds again.
1756 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001757void
Fred Drake100814d2000-07-09 15:48:49 +00001758_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001759{
1760 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00001761 PyObject *op = _PyTrash_delete_later;
Christian Heimes90aa7642007-12-19 02:45:37 +00001762 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001763
Neil Schemenauerf589c052002-03-29 03:05:54 +00001764 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00001765 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001766
Tim Peters803526b2002-07-07 05:13:56 +00001767 /* Call the deallocator directly. This used to try to
1768 * fool Py_DECREF into calling it indirectly, but
1769 * Py_DECREF was already called on this object, and in
1770 * assorted non-release builds calling Py_DECREF again ends
1771 * up distorting allocation statistics.
1772 */
1773 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00001774 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00001775 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00001776 --_PyTrash_delete_nesting;
1777 }
1778}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001779
1780#ifdef __cplusplus
1781}
1782#endif