blob: 4b210f10b578e734dce6400b7eac9eace6828d59 [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) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217 op->ob_type = 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;
229 op->ob_type = tp;
230 _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) {
274 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275 }
Guido van Rossum90933611991-06-07 16:10:43 +0000276 else {
277 if (op->ob_refcnt <= 0)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000278 /* XXX(twouters) cast refcount to long until %zd is
279 universally available */
280 fprintf(fp, "<refcnt %ld at %p>",
281 (long)op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000282 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000283 PyObject *s;
284 if (flags & Py_PRINT_RAW)
285 s = PyObject_Str(op);
286 else
287 s = PyObject_Repr(op);
288 if (s == NULL)
289 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000290 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000291 ret = internal_print(s, fp, Py_PRINT_RAW,
292 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000293 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000294 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000295 }
Guido van Rossum90933611991-06-07 16:10:43 +0000296 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000297 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000298 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000299 if (ret == 0) {
300 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000301 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000302 clearerr(fp);
303 ret = -1;
304 }
305 }
306 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307}
308
Neal Norwitz1a997502003-01-13 20:13:12 +0000309int
310PyObject_Print(PyObject *op, FILE *fp, int flags)
311{
312 return internal_print(op, fp, flags, 0);
313}
314
Guido van Rossum38938152006-08-21 23:36:26 +0000315/* For debugging convenience. Set a breakpoint here and call it from your DLL */
316void
Thomas Woutersb2137042007-02-01 18:02:27 +0000317_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000318{
319}
320
Neal Norwitz1a997502003-01-13 20:13:12 +0000321
Barry Warsaw9bf16442001-01-23 16:24:35 +0000322/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000323void
324_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000325{
Barry Warsaweefb1072001-02-22 22:39:18 +0000326 if (op == NULL)
327 fprintf(stderr, "NULL\n");
328 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000329 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000330 (void)PyObject_Print(op, stderr, 0);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000331 /* XXX(twouters) cast refcount to long until %zd is
332 universally available */
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000333 fprintf(stderr, "\n"
334 "type : %s\n"
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000335 "refcount: %ld\n"
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000336 "address : %p\n",
337 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000338 (long)op->ob_refcnt,
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000339 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000340 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000341}
Barry Warsaw903138f2001-01-23 16:33:18 +0000342
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000344PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000346 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000347 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000348#ifdef USE_STACKCHECK
349 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000350 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000351 return NULL;
352 }
353#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000354 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000356 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000357 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000358 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000359 else {
360 PyObject *res;
361 res = (*v->ob_type->tp_repr)(v);
362 if (res == NULL)
363 return NULL;
Guido van Rossumc8c82332007-05-04 05:14:29 +0000364 if (PyUnicode_Check(res))
365 return res;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000366 if (!PyString_Check(res)) {
367 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000368 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000369 res->ob_type->tp_name);
370 Py_DECREF(res);
371 return NULL;
372 }
373 return res;
374 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375}
376
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000378_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000379{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000380 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000381 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000382 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000383 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000384 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000385 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000386 return v;
387 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000388 if (PyUnicode_CheckExact(v)) {
389 Py_INCREF(v);
390 return v;
391 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000392 if (v->ob_type->tp_str == NULL)
393 return PyObject_Repr(v);
394
395 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000396 if (res == NULL)
397 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000398 type_ok = PyString_Check(res);
Neil Schemenauercf52c072005-08-12 17:34:58 +0000399 type_ok = type_ok || PyUnicode_Check(res);
Neil Schemenauercf52c072005-08-12 17:34:58 +0000400 if (!type_ok) {
401 PyErr_Format(PyExc_TypeError,
402 "__str__ returned non-string (type %.200s)",
403 res->ob_type->tp_name);
404 Py_DECREF(res);
405 return NULL;
406 }
407 return res;
408}
409
410PyObject *
411PyObject_Str(PyObject *v)
412{
413 PyObject *res = _PyObject_Str(v);
414 if (res == NULL)
415 return NULL;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000416 if (PyUnicode_Check(res)) {
417 PyObject* str;
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000418 str = _PyUnicode_AsDefaultEncodedString(res, NULL);
419 Py_XINCREF(str);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000420 Py_DECREF(res);
421 if (str)
422 res = str;
423 else
424 return NULL;
425 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000426 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000427 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000428}
429
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000430PyObject *
431PyObject_Unicode(PyObject *v)
432{
433 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000434 PyObject *func;
Neal Norwitz75801462006-03-14 06:02:16 +0000435 PyObject *str;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000436 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000437
Walter Dörwaldb03ccc02007-05-11 17:25:52 +0000438 if (v == NULL)
439 return PyUnicode_FromString("<NULL>");
440 else if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000441 Py_INCREF(v);
442 return v;
443 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000444 /* XXX As soon as we have a tp_unicode slot, we should
445 check this before trying the __unicode__
446 method. */
447 if (unicodestr == NULL) {
448 unicodestr= PyString_InternFromString("__unicode__");
449 if (unicodestr == NULL)
450 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000451 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000452 func = PyObject_GetAttr(v, unicodestr);
453 if (func != NULL) {
454 res = PyEval_CallObject(func, (PyObject *)NULL);
455 Py_DECREF(func);
456 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000457 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000458 PyErr_Clear();
459 if (PyUnicode_Check(v)) {
460 /* For a Unicode subtype that's didn't overwrite __unicode__,
461 return a true Unicode object with the same data. */
462 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
463 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000464 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000465 if (PyString_CheckExact(v)) {
466 Py_INCREF(v);
467 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000468 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000469 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000470 if (v->ob_type->tp_str != NULL)
471 res = (*v->ob_type->tp_str)(v);
472 else
473 res = PyObject_Repr(v);
474 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000475 }
476 if (res == NULL)
477 return NULL;
478 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000479 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000480 Py_DECREF(res);
Neal Norwitz75801462006-03-14 06:02:16 +0000481 res = str;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000482 }
483 return res;
484}
485
486
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000487/* The new comparison philosophy is: we completely separate three-way
488 comparison from rich comparison. That is, PyObject_Compare() and
489 PyObject_Cmp() *just* use the tp_compare slot. And PyObject_RichCompare()
490 and PyObject_RichCompareBool() *just* use the tp_richcompare slot.
491
492 See (*) below for practical amendments.
493
494 IOW, only cmp() uses tp_compare; the comparison operators (==, !=, <=, <,
495 >=, >) only use tp_richcompare. Note that list.sort() only uses <.
496
497 (And yes, eventually we'll rip out cmp() and tp_compare.)
498
499 The calling conventions are different: tp_compare only gets called with two
500 objects of the appropriate type; tp_richcompare gets called with a first
501 argument of the appropriate type and a second object of an arbitrary type.
502 We never do any kind of coercion.
503
504 The return conventions are also different.
505
506 The tp_compare slot should return a C int, as follows:
507
508 -1 if a < b or if an exception occurred
509 0 if a == b
510 +1 if a > b
511
512 No other return values are allowed. PyObject_Compare() has the same
513 calling convention.
514
515 The tp_richcompare slot should return an object, as follows:
516
517 NULL if an exception occurred
518 NotImplemented if the requested comparison is not implemented
519 any other false value if the requested comparison is false
520 any other true value if the requested comparison is true
521
522 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
523 NotImplemented.
524
525 (*) Practical amendments:
526
527 - If rich comparison returns NotImplemented, == and != are decided by
528 comparing the object pointer (i.e. falling back to the base object
529 implementation).
530
531 - If three-way comparison is not implemented, it falls back on rich
532 comparison (but not the other way around!).
533
Guido van Rossuma4073002002-05-31 20:03:54 +0000534*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000535
536/* Forward */
537static PyObject *do_richcompare(PyObject *v, PyObject *w, int op);
538
539/* Perform a three-way comparison, raising TypeError if three-way comparison
540 is not supported. */
Guido van Rossuma4073002002-05-31 20:03:54 +0000541static int
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000542do_compare(PyObject *v, PyObject *w)
Guido van Rossuma4073002002-05-31 20:03:54 +0000543{
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000544 cmpfunc f;
545 int ok;
546
547 if (v->ob_type == w->ob_type &&
548 (f = v->ob_type->tp_compare) != NULL) {
549 return (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000550 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000551
552 /* Now try three-way compare before giving up. This is intentionally
553 elaborate; if you have a it will raise TypeError if it detects two
554 objects that aren't ordered with respect to each other. */
555 ok = PyObject_RichCompareBool(v, w, Py_LT);
556 if (ok < 0)
557 return -1; /* Error */
558 if (ok)
559 return -1; /* Less than */
560 ok = PyObject_RichCompareBool(v, w, Py_GT);
561 if (ok < 0)
562 return -1; /* Error */
563 if (ok)
564 return 1; /* Greater than */
565 ok = PyObject_RichCompareBool(v, w, Py_EQ);
566 if (ok < 0)
567 return -1; /* Error */
568 if (ok)
569 return 0; /* Equal */
570
571 /* Give up */
572 PyErr_Format(PyExc_TypeError,
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000573 "unorderable types: '%.100s' != '%.100s'",
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000574 v->ob_type->tp_name,
575 w->ob_type->tp_name);
576 return -1;
Guido van Rossuma4073002002-05-31 20:03:54 +0000577}
578
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000579/* Perform a three-way comparison. This wraps do_compare() with a check for
580 NULL arguments and a recursion check. */
581int
582PyObject_Compare(PyObject *v, PyObject *w)
583{
584 int res;
Guido van Rossuma4073002002-05-31 20:03:54 +0000585
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000586 if (v == NULL || w == NULL) {
587 if (!PyErr_Occurred())
588 PyErr_BadInternalCall();
589 return -1;
590 }
591 if (Py_EnterRecursiveCall(" in cmp"))
592 return -1;
593 res = do_compare(v, w);
594 Py_LeaveRecursiveCall();
595 return res < 0 ? -1 : res;
596}
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000597
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000598/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000599int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000600
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000601static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000602
603/* Perform a rich comparison, raising TypeError when the requested comparison
604 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000605static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000606do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000607{
608 richcmpfunc f;
609 PyObject *res;
610
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000611 if (v->ob_type != w->ob_type &&
612 PyType_IsSubtype(w->ob_type, v->ob_type) &&
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000613 (f = w->ob_type->tp_richcompare) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000614 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000615 if (res != Py_NotImplemented)
616 return res;
617 Py_DECREF(res);
618 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000619 if ((f = v->ob_type->tp_richcompare) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000620 res = (*f)(v, w, op);
621 if (res != Py_NotImplemented)
622 return res;
623 Py_DECREF(res);
624 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000625 if ((f = w->ob_type->tp_richcompare) != NULL) {
626 res = (*f)(w, v, _Py_SwappedOp[op]);
627 if (res != Py_NotImplemented)
628 return res;
629 Py_DECREF(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000630 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000631 /* If neither object implements it, provide a sensible default
632 for == and !=, but raise an exception for ordering. */
633 switch (op) {
634 case Py_EQ:
635 res = (v == w) ? Py_True : Py_False;
636 break;
637 case Py_NE:
638 res = (v != w) ? Py_True : Py_False;
639 break;
640 default:
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000641 /* XXX Special-case None so it doesn't show as NoneType() */
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000642 PyErr_Format(PyExc_TypeError,
643 "unorderable types: %.100s() %s %.100s()",
644 v->ob_type->tp_name,
645 opstrings[op],
646 w->ob_type->tp_name);
647 return NULL;
648 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000649 Py_INCREF(res);
650 return res;
651}
652
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000653/* Perform a rich comparison with object result. This wraps do_richcompare()
654 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000655
Guido van Rossume797ec12001-01-17 15:24:28 +0000656PyObject *
657PyObject_RichCompare(PyObject *v, PyObject *w, int op)
658{
659 PyObject *res;
660
661 assert(Py_LT <= op && op <= Py_GE);
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000662 if (v == NULL || w == NULL) {
663 if (!PyErr_Occurred())
664 PyErr_BadInternalCall();
665 return NULL;
666 }
Armin Rigo2b3eb402003-10-28 12:05:48 +0000667 if (Py_EnterRecursiveCall(" in cmp"))
668 return NULL;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000669 res = do_richcompare(v, w, op);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000670 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000671 return res;
672}
673
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000674/* Perform a rich comparison with integer result. This wraps
675 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000676int
677PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
678{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000679 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000680 int ok;
681
Raymond Hettinger93d44812004-03-21 17:01:44 +0000682 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000683 if (res == NULL)
684 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000685 if (PyBool_Check(res))
686 ok = (res == Py_True);
687 else
688 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000689 Py_DECREF(res);
690 return ok;
691}
Fred Drake13634cf2000-06-29 19:17:04 +0000692
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000693/* Turn the result of a three-way comparison into the result expected by a
694 rich comparison. */
695PyObject *
696Py_CmpToRich(int op, int cmp)
697{
698 PyObject *res;
699 int ok;
700
701 if (PyErr_Occurred())
702 return NULL;
703 switch (op) {
704 case Py_LT:
705 ok = cmp < 0;
706 break;
707 case Py_LE:
708 ok = cmp <= 0;
709 break;
710 case Py_EQ:
711 ok = cmp == 0;
712 break;
713 case Py_NE:
714 ok = cmp != 0;
715 break;
716 case Py_GT:
717 ok = cmp > 0;
718 break;
719 case Py_GE:
720 ok = cmp >= 0;
721 break;
722 default:
723 PyErr_BadArgument();
724 return NULL;
725 }
726 res = ok ? Py_True : Py_False;
727 Py_INCREF(res);
728 return res;
729}
730
Fred Drake13634cf2000-06-29 19:17:04 +0000731/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000732 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000733
734 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
735*/
736
737long
Fred Drake100814d2000-07-09 15:48:49 +0000738_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000739{
Tim Peters39dce292000-08-15 03:34:48 +0000740 double intpart, fractpart;
741 int expo;
742 long hipart;
743 long x; /* the final hash value */
744 /* This is designed so that Python numbers of different types
745 * that compare equal hash to the same value; otherwise comparisons
746 * of mapping keys will turn out weird.
747 */
748
Tim Peters39dce292000-08-15 03:34:48 +0000749 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000750 if (fractpart == 0.0) {
751 /* This must return the same hash as an equal int or long. */
752 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
753 /* Convert to long and use its hash. */
754 PyObject *plong; /* converted to Python long */
755 if (Py_IS_INFINITY(intpart))
756 /* can't convert to long int -- arbitrary */
757 v = v < 0 ? -271828.0 : 314159.0;
758 plong = PyLong_FromDouble(v);
759 if (plong == NULL)
760 return -1;
761 x = PyObject_Hash(plong);
762 Py_DECREF(plong);
763 return x;
764 }
765 /* Fits in a C long == a Python int, so is its own hash. */
766 x = (long)intpart;
767 if (x == -1)
768 x = -2;
769 return x;
770 }
771 /* The fractional part is non-zero, so we don't have to worry about
772 * making this match the hash of some other type.
773 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000774 * Since the VAX D double format has 56 mantissa bits, which is the
775 * most of any double format in use, each of these parts may have as
776 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000777 * So, assuming sizeof(long) >= 4, each part can be broken into two
778 * longs; frexp and multiplication are used to do that.
779 * Also, since the Cray double format has 15 exponent bits, which is
780 * the most of any double format in use, shifting the exponent field
781 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000782 */
Tim Peters39dce292000-08-15 03:34:48 +0000783 v = frexp(v, &expo);
784 v *= 2147483648.0; /* 2**31 */
785 hipart = (long)v; /* take the top 32 bits */
786 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
787 x = hipart + (long)v + (expo << 15);
788 if (x == -1)
789 x = -2;
790 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000791}
792
793long
Fred Drake100814d2000-07-09 15:48:49 +0000794_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000795{
796#if SIZEOF_LONG >= SIZEOF_VOID_P
797 return (long)p;
798#else
799 /* convert to a Python long and hash that */
800 PyObject* longobj;
801 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000802
Fred Drake13634cf2000-06-29 19:17:04 +0000803 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
804 x = -1;
805 goto finally;
806 }
807 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000808
Fred Drake13634cf2000-06-29 19:17:04 +0000809finally:
810 Py_XDECREF(longobj);
811 return x;
812#endif
813}
814
815
Guido van Rossum9bfef441993-03-29 10:43:31 +0000816long
Fred Drake100814d2000-07-09 15:48:49 +0000817PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000818{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000819 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000820 if (tp->tp_hash != NULL)
821 return (*tp->tp_hash)(v);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000822 /* Otherwise, the object can't be hashed */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000823 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
824 v->ob_type->tp_name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000825 return -1;
826}
827
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000828PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000829PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000830{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000832
Tim Peters6d6c1a32001-08-02 04:15:00 +0000833 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000834 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000835 w = PyString_InternFromString(name);
836 if (w == NULL)
837 return NULL;
838 res = PyObject_GetAttr(v, w);
839 Py_XDECREF(w);
840 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000841}
842
843int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000844PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000845{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000846 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000847 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000848 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000849 return 1;
850 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000851 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000852 return 0;
853}
854
855int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000856PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000857{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000858 PyObject *s;
859 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000860
Tim Peters6d6c1a32001-08-02 04:15:00 +0000861 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000862 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000863 s = PyString_InternFromString(name);
864 if (s == NULL)
865 return -1;
866 res = PyObject_SetAttr(v, s, w);
867 Py_XDECREF(s);
868 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000869}
870
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000871PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000872PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000873{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874 PyTypeObject *tp = v->ob_type;
875
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000876 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000877 /* The Unicode to string conversion is done here because the
878 existing tp_getattro slots expect a string object as name
879 and we wouldn't want to break those. */
880 if (PyUnicode_Check(name)) {
881 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
882 if (name == NULL)
883 return NULL;
884 }
885 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000886 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000887 PyErr_Format(PyExc_TypeError,
888 "attribute name must be string, not '%.200s'",
889 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000890 return NULL;
891 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000892 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893 if (tp->tp_getattro != NULL)
894 return (*tp->tp_getattro)(v, name);
895 if (tp->tp_getattr != NULL)
896 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
897 PyErr_Format(PyExc_AttributeError,
898 "'%.50s' object has no attribute '%.400s'",
899 tp->tp_name, PyString_AS_STRING(name));
900 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000901}
902
903int
Fred Drake100814d2000-07-09 15:48:49 +0000904PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000905{
906 PyObject *res = PyObject_GetAttr(v, name);
907 if (res != NULL) {
908 Py_DECREF(res);
909 return 1;
910 }
911 PyErr_Clear();
912 return 0;
913}
914
915int
Fred Drake100814d2000-07-09 15:48:49 +0000916PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000917{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000918 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000919 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000920
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000921 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000922 /* The Unicode to string conversion is done here because the
923 existing tp_setattro slots expect a string object as name
924 and we wouldn't want to break those. */
925 if (PyUnicode_Check(name)) {
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000926 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000927 if (name == NULL)
928 return -1;
929 }
Tim Peters803526b2002-07-07 05:13:56 +0000930 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000931 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000932 PyErr_Format(PyExc_TypeError,
933 "attribute name must be string, not '%.200s'",
934 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000935 return -1;
936 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000937 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000938 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000939
940 PyString_InternInPlace(&name);
941 if (tp->tp_setattro != NULL) {
942 err = (*tp->tp_setattro)(v, name, value);
943 Py_DECREF(name);
944 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000945 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000946 if (tp->tp_setattr != NULL) {
947 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
948 Py_DECREF(name);
949 return err;
950 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000951 Py_DECREF(name);
Guido van Rossumf15a29f2007-05-04 00:41:39 +0000952 assert(name->ob_refcnt >= 1);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000953 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
954 PyErr_Format(PyExc_TypeError,
955 "'%.100s' object has no attributes "
956 "(%s .%.100s)",
957 tp->tp_name,
958 value==NULL ? "del" : "assign to",
959 PyString_AS_STRING(name));
960 else
961 PyErr_Format(PyExc_TypeError,
962 "'%.100s' object has only read-only attributes "
963 "(%s .%.100s)",
964 tp->tp_name,
965 value==NULL ? "del" : "assign to",
966 PyString_AS_STRING(name));
967 return -1;
968}
969
970/* Helper to get a pointer to an object's __dict__ slot, if any */
971
972PyObject **
973_PyObject_GetDictPtr(PyObject *obj)
974{
Martin v. Löwis725507b2006-03-07 12:08:51 +0000975 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000976 PyTypeObject *tp = obj->ob_type;
977
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978 dictoffset = tp->tp_dictoffset;
979 if (dictoffset == 0)
980 return NULL;
981 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000982 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000983 size_t size;
984
985 tsize = ((PyVarObject *)obj)->ob_size;
986 if (tsize < 0)
987 tsize = -tsize;
988 size = _PyObject_VAR_SIZE(tp, tsize);
989
Tim Peters6d483d32001-10-06 21:27:34 +0000990 dictoffset += (long)size;
991 assert(dictoffset > 0);
992 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993 }
994 return (PyObject **) ((char *)obj + dictoffset);
995}
996
Tim Peters6d6c1a32001-08-02 04:15:00 +0000997PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +0000998PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +0000999{
1000 Py_INCREF(obj);
1001 return obj;
1002}
1003
Michael W. Hudson1593f502004-09-14 17:09:47 +00001004/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1005
Raymond Hettinger01538262003-03-17 08:24:35 +00001006PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1008{
1009 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001010 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001011 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001012 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001013 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014 PyObject **dictptr;
1015
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001016 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001017 /* The Unicode to string conversion is done here because the
1018 existing tp_setattro slots expect a string object as name
1019 and we wouldn't want to break those. */
1020 if (PyUnicode_Check(name)) {
1021 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1022 if (name == NULL)
1023 return NULL;
1024 }
Tim Peters803526b2002-07-07 05:13:56 +00001025 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001026 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001027 PyErr_Format(PyExc_TypeError,
1028 "attribute name must be string, not '%.200s'",
1029 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001030 return NULL;
1031 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001032 }
1033 else
1034 Py_INCREF(name);
1035
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001037 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001038 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 }
1040
Guido van Rossum056fbf42002-08-19 19:22:50 +00001041 /* Inline _PyType_Lookup */
1042 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001043 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001044 PyObject *mro, *base, *dict;
1045
1046 /* Look in tp_dict of types in MRO */
1047 mro = tp->tp_mro;
1048 assert(mro != NULL);
1049 assert(PyTuple_Check(mro));
1050 n = PyTuple_GET_SIZE(mro);
1051 for (i = 0; i < n; i++) {
1052 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001053 assert(PyType_Check(base));
1054 dict = ((PyTypeObject *)base)->tp_dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001055 assert(dict && PyDict_Check(dict));
1056 descr = PyDict_GetItem(dict, name);
1057 if (descr != NULL)
1058 break;
1059 }
1060 }
1061
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001062 Py_XINCREF(descr);
1063
Tim Peters6d6c1a32001-08-02 04:15:00 +00001064 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001065 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001067 if (f != NULL && PyDescr_IsData(descr)) {
1068 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001069 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001070 goto done;
1071 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072 }
1073
Guido van Rossumc66ff442002-08-19 16:50:48 +00001074 /* Inline _PyObject_GetDictPtr */
1075 dictoffset = tp->tp_dictoffset;
1076 if (dictoffset != 0) {
1077 PyObject *dict;
1078 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001079 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001080 size_t size;
1081
1082 tsize = ((PyVarObject *)obj)->ob_size;
1083 if (tsize < 0)
1084 tsize = -tsize;
1085 size = _PyObject_VAR_SIZE(tp, tsize);
1086
1087 dictoffset += (long)size;
1088 assert(dictoffset > 0);
1089 assert(dictoffset % SIZEOF_VOID_P == 0);
1090 }
1091 dictptr = (PyObject **) ((char *)obj + dictoffset);
1092 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001094 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095 if (res != NULL) {
1096 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001097 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001098 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 }
1100 }
1101 }
1102
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001103 if (f != NULL) {
1104 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001105 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001106 goto done;
1107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108
1109 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001110 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001111 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001112 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 }
1114
1115 PyErr_Format(PyExc_AttributeError,
1116 "'%.50s' object has no attribute '%.400s'",
1117 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001118 done:
1119 Py_DECREF(name);
1120 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121}
1122
1123int
1124PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1125{
1126 PyTypeObject *tp = obj->ob_type;
1127 PyObject *descr;
1128 descrsetfunc f;
1129 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001130 int res = -1;
1131
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001132 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001133 /* The Unicode to string conversion is done here because the
1134 existing tp_setattro slots expect a string object as name
1135 and we wouldn't want to break those. */
1136 if (PyUnicode_Check(name)) {
1137 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1138 if (name == NULL)
1139 return -1;
1140 }
Tim Peters803526b2002-07-07 05:13:56 +00001141 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001142 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001143 PyErr_Format(PyExc_TypeError,
1144 "attribute name must be string, not '%.200s'",
1145 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001146 return -1;
1147 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001148 }
1149 else
1150 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151
1152 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001153 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001154 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 }
1156
1157 descr = _PyType_Lookup(tp, name);
1158 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001159 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001161 if (f != NULL && PyDescr_IsData(descr)) {
1162 res = f(descr, obj, value);
1163 goto done;
1164 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001165 }
1166
1167 dictptr = _PyObject_GetDictPtr(obj);
1168 if (dictptr != NULL) {
1169 PyObject *dict = *dictptr;
1170 if (dict == NULL && value != NULL) {
1171 dict = PyDict_New();
1172 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001173 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174 *dictptr = dict;
1175 }
1176 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177 if (value == NULL)
1178 res = PyDict_DelItem(dict, name);
1179 else
1180 res = PyDict_SetItem(dict, name, value);
1181 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1182 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001183 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184 }
1185 }
1186
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001187 if (f != NULL) {
1188 res = f(descr, obj, value);
1189 goto done;
1190 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191
1192 if (descr == NULL) {
1193 PyErr_Format(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001194 "'%.100s' object has no attribute '%.200s'",
Tim Peters6d6c1a32001-08-02 04:15:00 +00001195 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001196 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001197 }
1198
1199 PyErr_Format(PyExc_AttributeError,
1200 "'%.50s' object attribute '%.400s' is read-only",
1201 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001202 done:
1203 Py_DECREF(name);
1204 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001205}
1206
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001207/* Test a value used as condition, e.g., in a for or if statement.
1208 Return -1 if an error occurred */
1209
1210int
Fred Drake100814d2000-07-09 15:48:49 +00001211PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001212{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001213 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001214 if (v == Py_True)
1215 return 1;
1216 if (v == Py_False)
1217 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001218 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001219 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001220 else if (v->ob_type->tp_as_number != NULL &&
Jack Diederich4dafcc42006-11-28 19:15:13 +00001221 v->ob_type->tp_as_number->nb_bool != NULL)
1222 res = (*v->ob_type->tp_as_number->nb_bool)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001223 else if (v->ob_type->tp_as_mapping != NULL &&
1224 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001225 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001226 else if (v->ob_type->tp_as_sequence != NULL &&
1227 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001228 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1229 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001230 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001231 /* if it is negative, it should be either -1 or -2 */
1232 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001233}
1234
Tim Peters803526b2002-07-07 05:13:56 +00001235/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001236 Return -1 if an error occurred */
1237
1238int
Fred Drake100814d2000-07-09 15:48:49 +00001239PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001240{
1241 int res;
1242 res = PyObject_IsTrue(v);
1243 if (res < 0)
1244 return res;
1245 return res == 0;
1246}
1247
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001248/* Test whether an object can be called */
1249
1250int
Fred Drake100814d2000-07-09 15:48:49 +00001251PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001252{
1253 if (x == NULL)
1254 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001255 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001256}
1257
Georg Brandle32b4222007-03-10 22:13:27 +00001258/* ------------------------- PyObject_Dir() helpers ------------------------- */
1259
Tim Peters7eea37e2001-09-04 22:08:56 +00001260/* Helper for PyObject_Dir.
1261 Merge the __dict__ of aclass into dict, and recursively also all
1262 the __dict__s of aclass's base classes. The order of merging isn't
1263 defined, as it's expected that only the final set of dict keys is
1264 interesting.
1265 Return 0 on success, -1 on error.
1266*/
1267
1268static int
1269merge_class_dict(PyObject* dict, PyObject* aclass)
1270{
1271 PyObject *classdict;
1272 PyObject *bases;
1273
1274 assert(PyDict_Check(dict));
1275 assert(aclass);
1276
1277 /* Merge in the type's dict (if any). */
1278 classdict = PyObject_GetAttrString(aclass, "__dict__");
1279 if (classdict == NULL)
1280 PyErr_Clear();
1281 else {
1282 int status = PyDict_Update(dict, classdict);
1283 Py_DECREF(classdict);
1284 if (status < 0)
1285 return -1;
1286 }
1287
1288 /* Recursively merge in the base types' (if any) dicts. */
1289 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001290 if (bases == NULL)
1291 PyErr_Clear();
1292 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001293 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001294 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001295 n = PySequence_Size(bases); /* This better be right */
1296 if (n < 0)
1297 PyErr_Clear();
1298 else {
1299 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001300 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001301 PyObject *base = PySequence_GetItem(bases, i);
1302 if (base == NULL) {
1303 Py_DECREF(bases);
1304 return -1;
1305 }
Tim Peters18e70832003-02-05 19:35:19 +00001306 status = merge_class_dict(dict, base);
1307 Py_DECREF(base);
1308 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001309 Py_DECREF(bases);
1310 return -1;
1311 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001312 }
1313 }
1314 Py_DECREF(bases);
1315 }
1316 return 0;
1317}
1318
Georg Brandle32b4222007-03-10 22:13:27 +00001319/* Helper for PyObject_Dir without arguments: returns the local scope. */
1320static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001321_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001322{
Georg Brandled3b8382007-03-12 13:15:14 +00001323 PyObject *names;
Georg Brandle32b4222007-03-10 22:13:27 +00001324 PyObject *locals = PyEval_GetLocals();
Tim Peters305b5852001-09-17 02:38:46 +00001325
Georg Brandle32b4222007-03-10 22:13:27 +00001326 if (locals == NULL) {
1327 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1328 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001329 }
1330
Georg Brandled3b8382007-03-12 13:15:14 +00001331 names = PyMapping_Keys(locals);
1332 if (!names)
1333 return NULL;
1334 if (!PyList_Check(names)) {
1335 PyErr_Format(PyExc_TypeError,
1336 "dir(): expected keys() of locals to be a list, "
1337 "not '%.200s'", names->ob_type->tp_name);
1338 Py_DECREF(names);
1339 return NULL;
1340 }
Georg Brandle32b4222007-03-10 22:13:27 +00001341 /* the locals don't need to be DECREF'd */
Georg Brandled3b8382007-03-12 13:15:14 +00001342 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001343}
1344
1345/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
1346 We deliberately don't suck up its __class__, as methods belonging to the
1347 metaclass would probably be more confusing than helpful.
1348*/
1349static PyObject *
1350_specialized_dir_type(PyObject *obj)
1351{
1352 PyObject *result = NULL;
1353 PyObject *dict = PyDict_New();
1354
1355 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1356 result = PyDict_Keys(dict);
1357
1358 Py_XDECREF(dict);
Tim Peters305b5852001-09-17 02:38:46 +00001359 return result;
1360}
1361
Georg Brandle32b4222007-03-10 22:13:27 +00001362/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1363static PyObject *
1364_specialized_dir_module(PyObject *obj)
Tim Peters7eea37e2001-09-04 22:08:56 +00001365{
Georg Brandle32b4222007-03-10 22:13:27 +00001366 PyObject *result = NULL;
1367 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Tim Peters7eea37e2001-09-04 22:08:56 +00001368
Georg Brandle32b4222007-03-10 22:13:27 +00001369 if (dict != NULL) {
1370 if (PyDict_Check(dict))
1371 result = PyDict_Keys(dict);
1372 else {
1373 PyErr_Format(PyExc_TypeError,
1374 "%.200s.__dict__ is not a dictionary",
1375 PyModule_GetName(obj));
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001376 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001377 }
1378
Georg Brandle32b4222007-03-10 22:13:27 +00001379 Py_XDECREF(dict);
1380 return result;
1381}
Tim Peters7eea37e2001-09-04 22:08:56 +00001382
Georg Brandle32b4222007-03-10 22:13:27 +00001383/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1384 and recursively up the __class__.__bases__ chain.
1385*/
1386static PyObject *
1387_generic_dir(PyObject *obj)
1388{
1389 PyObject *result = NULL;
1390 PyObject *dict = NULL;
1391 PyObject *itsclass = NULL;
1392
1393 /* Get __dict__ (which may or may not be a real dict...) */
1394 dict = PyObject_GetAttrString(obj, "__dict__");
1395 if (dict == NULL) {
1396 PyErr_Clear();
1397 dict = PyDict_New();
1398 }
1399 else if (!PyDict_Check(dict)) {
1400 Py_DECREF(dict);
1401 dict = PyDict_New();
1402 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001403 else {
Georg Brandle32b4222007-03-10 22:13:27 +00001404 /* Copy __dict__ to avoid mutating it. */
1405 PyObject *temp = PyDict_Copy(dict);
1406 Py_DECREF(dict);
1407 dict = temp;
Tim Peters7eea37e2001-09-04 22:08:56 +00001408 }
1409
Georg Brandle32b4222007-03-10 22:13:27 +00001410 if (dict == NULL)
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001411 goto error;
Tim Peters7eea37e2001-09-04 22:08:56 +00001412
Georg Brandle32b4222007-03-10 22:13:27 +00001413 /* Merge in attrs reachable from its class. */
1414 itsclass = PyObject_GetAttrString(obj, "__class__");
1415 if (itsclass == NULL)
1416 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1417 __class__ exists? */
1418 PyErr_Clear();
1419 else {
1420 if (merge_class_dict(dict, itsclass) != 0)
1421 goto error;
1422 }
1423
1424 result = PyDict_Keys(dict);
Tim Peters7eea37e2001-09-04 22:08:56 +00001425 /* fall through */
Georg Brandle32b4222007-03-10 22:13:27 +00001426error:
1427 Py_XDECREF(itsclass);
1428 Py_XDECREF(dict);
1429 return result;
1430}
1431
1432/* Helper for PyObject_Dir: object introspection.
1433 This calls one of the above specialized versions if no __dir__ method
1434 exists. */
1435static PyObject *
1436_dir_object(PyObject *obj)
1437{
1438 PyObject * result = NULL;
1439 PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type,
1440 "__dir__");
1441
1442 assert(obj);
1443 if (dirfunc == NULL) {
1444 /* use default implementation */
1445 PyErr_Clear();
1446 if (PyModule_Check(obj))
1447 result = _specialized_dir_module(obj);
1448 else if (PyType_Check(obj))
1449 result = _specialized_dir_type(obj);
1450 else
1451 result = _generic_dir(obj);
1452 }
1453 else {
1454 /* use __dir__ */
1455 result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
1456 Py_DECREF(dirfunc);
1457 if (result == NULL)
1458 return NULL;
1459
1460 /* result must be a list */
1461 /* XXX(gbrandl): could also check if all items are strings */
1462 if (!PyList_Check(result)) {
1463 PyErr_Format(PyExc_TypeError,
1464 "__dir__() must return a list, not %.200s",
1465 result->ob_type->tp_name);
1466 Py_DECREF(result);
1467 result = NULL;
1468 }
1469 }
1470
1471 return result;
1472}
1473
1474/* Implementation of dir() -- if obj is NULL, returns the names in the current
1475 (local) scope. Otherwise, performs introspection of the object: returns a
1476 sorted list of attribute names (supposedly) accessible from the object
1477*/
1478PyObject *
1479PyObject_Dir(PyObject *obj)
1480{
1481 PyObject * result;
1482
1483 if (obj == NULL)
1484 /* no object -- introspect the locals */
1485 result = _dir_locals();
1486 else
1487 /* object -- introspect the object */
1488 result = _dir_object(obj);
1489
1490 assert(result == NULL || PyList_Check(result));
1491
1492 if (result != NULL && PyList_Sort(result) != 0) {
1493 /* sorting the list failed */
1494 Py_DECREF(result);
1495 result = NULL;
1496 }
1497
Tim Peters7eea37e2001-09-04 22:08:56 +00001498 return result;
1499}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001500
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001501/*
1502NoObject is usable as a non-NULL undefined value, used by the macro None.
1503There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001504so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001505(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001506*/
1507
Guido van Rossum0c182a11992-03-27 17:26:13 +00001508/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001509static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001510none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001511{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001512 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001513}
1514
Barry Warsaw9bf16442001-01-23 16:24:35 +00001515/* ARGUSED */
1516static void
Tim Peters803526b2002-07-07 05:13:56 +00001517none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001518{
1519 /* This should never get called, but we also don't want to SEGV if
1520 * we accidently decref None out of existance.
1521 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001522 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001523}
1524
1525
Guido van Rossumba21a492001-08-16 08:17:26 +00001526static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001527 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001528 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001529 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530 0,
1531 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001532 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001533 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001534 0, /*tp_getattr*/
1535 0, /*tp_setattr*/
1536 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001537 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001538 0, /*tp_as_number*/
1539 0, /*tp_as_sequence*/
1540 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001541 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001542};
1543
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001544PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001545 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001546};
1547
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001548/* NotImplemented is an object that can be used to signal that an
1549 operation is not implemented for the given type combination. */
1550
1551static PyObject *
1552NotImplemented_repr(PyObject *op)
1553{
1554 return PyString_FromString("NotImplemented");
1555}
1556
1557static PyTypeObject PyNotImplemented_Type = {
1558 PyObject_HEAD_INIT(&PyType_Type)
1559 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001560 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001561 0,
1562 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001563 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001564 0, /*tp_print*/
1565 0, /*tp_getattr*/
1566 0, /*tp_setattr*/
1567 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001568 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001569 0, /*tp_as_number*/
1570 0, /*tp_as_sequence*/
1571 0, /*tp_as_mapping*/
1572 0, /*tp_hash */
1573};
1574
1575PyObject _Py_NotImplementedStruct = {
1576 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1577};
1578
Guido van Rossumba21a492001-08-16 08:17:26 +00001579void
1580_Py_ReadyTypes(void)
1581{
1582 if (PyType_Ready(&PyType_Type) < 0)
1583 Py_FatalError("Can't initialize 'type'");
1584
Fred Drake0a4dd392004-07-02 18:57:45 +00001585 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1586 Py_FatalError("Can't initialize 'weakref'");
1587
Guido van Rossum77f6a652002-04-03 22:41:51 +00001588 if (PyType_Ready(&PyBool_Type) < 0)
1589 Py_FatalError("Can't initialize 'bool'");
1590
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001591 if (PyType_Ready(&PyBytes_Type) < 0)
1592 Py_FatalError("Can't initialize 'bytes'");
1593
Guido van Rossumcacfc072002-05-24 19:01:59 +00001594 if (PyType_Ready(&PyString_Type) < 0)
1595 Py_FatalError("Can't initialize 'str'");
1596
Guido van Rossumba21a492001-08-16 08:17:26 +00001597 if (PyType_Ready(&PyList_Type) < 0)
1598 Py_FatalError("Can't initialize 'list'");
1599
1600 if (PyType_Ready(&PyNone_Type) < 0)
1601 Py_FatalError("Can't initialize type(None)");
1602
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001603 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1604 Py_FatalError("Can't initialize type(Ellipsis)");
1605
Guido van Rossumba21a492001-08-16 08:17:26 +00001606 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1607 Py_FatalError("Can't initialize type(NotImplemented)");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001608
1609 if (PyType_Ready(&PyCode_Type) < 0)
1610 Py_FatalError("Can't initialize 'code'");
Guido van Rossumba21a492001-08-16 08:17:26 +00001611}
1612
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001613
Guido van Rossum84a90321996-05-22 16:34:47 +00001614#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001615
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001616void
Fred Drake100814d2000-07-09 15:48:49 +00001617_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001618{
Tim Peters34592512002-07-11 06:23:50 +00001619 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001620 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001621 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001622 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001623}
1624
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001625void
Fred Drake100814d2000-07-09 15:48:49 +00001626_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001627{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001628#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001629 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001630#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001631 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001632 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001633 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001634 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001635 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001636#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001637 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1638 if (p == op)
1639 break;
1640 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001641 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001643#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001644 op->_ob_next->_ob_prev = op->_ob_prev;
1645 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001646 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001647 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001648}
1649
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001650void
Fred Drake100814d2000-07-09 15:48:49 +00001651_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001652{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001653 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001654 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001655 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001656}
1657
Tim Peters269b2a62003-04-17 19:52:29 +00001658/* Print all live objects. Because PyObject_Print is called, the
1659 * interpreter must be in a healthy state.
1660 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001661void
Fred Drake100814d2000-07-09 15:48:49 +00001662_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001663{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001664 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001665 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001666 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001667 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001668 if (PyObject_Print(op, fp, 0) != 0)
1669 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001670 putc('\n', fp);
1671 }
1672}
1673
Tim Peters269b2a62003-04-17 19:52:29 +00001674/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1675 * doesn't make any calls to the Python C API, so is always safe to call.
1676 */
1677void
1678_Py_PrintReferenceAddresses(FILE *fp)
1679{
1680 PyObject *op;
1681 fprintf(fp, "Remaining object addresses:\n");
1682 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001683 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1684 op->ob_refcnt, op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001685}
1686
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001687PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001688_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001689{
1690 int i, n;
1691 PyObject *t = NULL;
1692 PyObject *res, *op;
1693
1694 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1695 return NULL;
1696 op = refchain._ob_next;
1697 res = PyList_New(0);
1698 if (res == NULL)
1699 return NULL;
1700 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1701 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001702 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001703 op = op->_ob_next;
1704 if (op == &refchain)
1705 return res;
1706 }
1707 if (PyList_Append(res, op) < 0) {
1708 Py_DECREF(res);
1709 return NULL;
1710 }
1711 op = op->_ob_next;
1712 }
1713 return res;
1714}
1715
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001716#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001717
1718
1719/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001720PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001721
1722
1723/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001724Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001725
1726
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001727/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001728
Thomas Wouters334fb892000-07-25 12:56:38 +00001729void *
Fred Drake100814d2000-07-09 15:48:49 +00001730PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001731{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001732 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001733}
1734
Thomas Wouters334fb892000-07-25 12:56:38 +00001735void *
1736PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001737{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001738 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001739}
1740
1741void
Thomas Wouters334fb892000-07-25 12:56:38 +00001742PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001743{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001744 PyMem_FREE(p);
1745}
1746
1747
Guido van Rossum86610361998-04-10 22:32:46 +00001748/* These methods are used to control infinite recursion in repr, str, print,
1749 etc. Container objects that may recursively contain themselves,
1750 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1751 Py_ReprLeave() to avoid infinite recursion.
1752
1753 Py_ReprEnter() returns 0 the first time it is called for a particular
1754 object and 1 every time thereafter. It returns -1 if an exception
1755 occurred. Py_ReprLeave() has no return value.
1756
1757 See dictobject.c and listobject.c for examples of use.
1758*/
1759
1760#define KEY "Py_Repr"
1761
1762int
Fred Drake100814d2000-07-09 15:48:49 +00001763Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001764{
1765 PyObject *dict;
1766 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001767 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001768
1769 dict = PyThreadState_GetDict();
1770 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001771 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001772 list = PyDict_GetItemString(dict, KEY);
1773 if (list == NULL) {
1774 list = PyList_New(0);
1775 if (list == NULL)
1776 return -1;
1777 if (PyDict_SetItemString(dict, KEY, list) < 0)
1778 return -1;
1779 Py_DECREF(list);
1780 }
1781 i = PyList_GET_SIZE(list);
1782 while (--i >= 0) {
1783 if (PyList_GET_ITEM(list, i) == obj)
1784 return 1;
1785 }
1786 PyList_Append(list, obj);
1787 return 0;
1788}
1789
1790void
Fred Drake100814d2000-07-09 15:48:49 +00001791Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001792{
1793 PyObject *dict;
1794 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001795 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001796
1797 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001798 if (dict == NULL)
1799 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001800 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001801 if (list == NULL || !PyList_Check(list))
1802 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001803 i = PyList_GET_SIZE(list);
1804 /* Count backwards because we always expect obj to be list[-1] */
1805 while (--i >= 0) {
1806 if (PyList_GET_ITEM(list, i) == obj) {
1807 PyList_SetSlice(list, i, i + 1, NULL);
1808 break;
1809 }
1810 }
1811}
Guido van Rossumd724b232000-03-13 16:01:29 +00001812
Tim Peters803526b2002-07-07 05:13:56 +00001813/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001814
Tim Peters803526b2002-07-07 05:13:56 +00001815/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001816int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001817
Tim Peters803526b2002-07-07 05:13:56 +00001818/* List of objects that still need to be cleaned up, singly linked via their
1819 * gc headers' gc_prev pointers.
1820 */
1821PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001822
Tim Peters803526b2002-07-07 05:13:56 +00001823/* Add op to the _PyTrash_delete_later list. Called when the current
1824 * call-stack depth gets large. op must be a currently untracked gc'ed
1825 * object, with refcount 0. Py_DECREF must already have been called on it.
1826 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001827void
Fred Drake100814d2000-07-09 15:48:49 +00001828_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001829{
Tim Peters803526b2002-07-07 05:13:56 +00001830 assert(PyObject_IS_GC(op));
1831 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1832 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00001833 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001834 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001835}
1836
Tim Peters803526b2002-07-07 05:13:56 +00001837/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1838 * the call-stack unwinds again.
1839 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001840void
Fred Drake100814d2000-07-09 15:48:49 +00001841_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001842{
1843 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00001844 PyObject *op = _PyTrash_delete_later;
1845 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001846
Neil Schemenauerf589c052002-03-29 03:05:54 +00001847 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00001848 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001849
Tim Peters803526b2002-07-07 05:13:56 +00001850 /* Call the deallocator directly. This used to try to
1851 * fool Py_DECREF into calling it indirectly, but
1852 * Py_DECREF was already called on this object, and in
1853 * assorted non-release builds calling Py_DECREF again ends
1854 * up distorting allocation statistics.
1855 */
1856 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00001857 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00001858 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00001859 --_PyTrash_delete_nesting;
1860 }
1861}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001862
1863#ifdef __cplusplus
1864}
1865#endif