blob: 0bf0c605551fd9c7ddf4e0e98af34fd6ee08ad49 [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;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000364#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000365 if (PyUnicode_Check(res)) {
366 PyObject* str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000367 str = PyUnicode_AsEncodedString(res, NULL, NULL);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000368 Py_DECREF(res);
369 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000370 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000371 else
372 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000373 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000374#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000375 if (!PyString_Check(res)) {
376 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000377 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000378 res->ob_type->tp_name);
379 Py_DECREF(res);
380 return NULL;
381 }
382 return res;
383 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384}
385
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000387_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000388{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000389 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000390 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000391 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000392 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000393 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000395 return v;
396 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000397#ifdef Py_USING_UNICODE
398 if (PyUnicode_CheckExact(v)) {
399 Py_INCREF(v);
400 return v;
401 }
402#endif
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000403 if (v->ob_type->tp_str == NULL)
404 return PyObject_Repr(v);
405
406 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000407 if (res == NULL)
408 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000409 type_ok = PyString_Check(res);
410#ifdef Py_USING_UNICODE
411 type_ok = type_ok || PyUnicode_Check(res);
412#endif
413 if (!type_ok) {
414 PyErr_Format(PyExc_TypeError,
415 "__str__ returned non-string (type %.200s)",
416 res->ob_type->tp_name);
417 Py_DECREF(res);
418 return NULL;
419 }
420 return res;
421}
422
423PyObject *
424PyObject_Str(PyObject *v)
425{
426 PyObject *res = _PyObject_Str(v);
427 if (res == NULL)
428 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000429#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000430 if (PyUnicode_Check(res)) {
431 PyObject* str;
432 str = PyUnicode_AsEncodedString(res, NULL, NULL);
433 Py_DECREF(res);
434 if (str)
435 res = str;
436 else
437 return NULL;
438 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000439#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +0000440 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000441 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000442}
443
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000444#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000445PyObject *
446PyObject_Unicode(PyObject *v)
447{
448 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000449 PyObject *func;
Neal Norwitz75801462006-03-14 06:02:16 +0000450 PyObject *str;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000451 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000452
Georg Brandl3daf7582006-03-13 22:22:11 +0000453 if (v == NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000454 res = PyString_FromString("<NULL>");
Neal Norwitz75801462006-03-14 06:02:16 +0000455 if (res == NULL)
456 return NULL;
457 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
458 Py_DECREF(res);
459 return str;
Georg Brandl3daf7582006-03-13 22:22:11 +0000460 } else if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000461 Py_INCREF(v);
462 return v;
463 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000464 /* XXX As soon as we have a tp_unicode slot, we should
465 check this before trying the __unicode__
466 method. */
467 if (unicodestr == NULL) {
468 unicodestr= PyString_InternFromString("__unicode__");
469 if (unicodestr == NULL)
470 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000471 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000472 func = PyObject_GetAttr(v, unicodestr);
473 if (func != NULL) {
474 res = PyEval_CallObject(func, (PyObject *)NULL);
475 Py_DECREF(func);
476 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000477 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000478 PyErr_Clear();
479 if (PyUnicode_Check(v)) {
480 /* For a Unicode subtype that's didn't overwrite __unicode__,
481 return a true Unicode object with the same data. */
482 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
483 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000484 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000485 if (PyString_CheckExact(v)) {
486 Py_INCREF(v);
487 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000488 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000489 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000490 if (v->ob_type->tp_str != NULL)
491 res = (*v->ob_type->tp_str)(v);
492 else
493 res = PyObject_Repr(v);
494 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000495 }
496 if (res == NULL)
497 return NULL;
498 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000499 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000500 Py_DECREF(res);
Neal Norwitz75801462006-03-14 06:02:16 +0000501 res = str;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000502 }
503 return res;
504}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000505#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000506
507
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000508/* The new comparison philosophy is: we completely separate three-way
509 comparison from rich comparison. That is, PyObject_Compare() and
510 PyObject_Cmp() *just* use the tp_compare slot. And PyObject_RichCompare()
511 and PyObject_RichCompareBool() *just* use the tp_richcompare slot.
512
513 See (*) below for practical amendments.
514
515 IOW, only cmp() uses tp_compare; the comparison operators (==, !=, <=, <,
516 >=, >) only use tp_richcompare. Note that list.sort() only uses <.
517
518 (And yes, eventually we'll rip out cmp() and tp_compare.)
519
520 The calling conventions are different: tp_compare only gets called with two
521 objects of the appropriate type; tp_richcompare gets called with a first
522 argument of the appropriate type and a second object of an arbitrary type.
523 We never do any kind of coercion.
524
525 The return conventions are also different.
526
527 The tp_compare slot should return a C int, as follows:
528
529 -1 if a < b or if an exception occurred
530 0 if a == b
531 +1 if a > b
532
533 No other return values are allowed. PyObject_Compare() has the same
534 calling convention.
535
536 The tp_richcompare slot should return an object, as follows:
537
538 NULL if an exception occurred
539 NotImplemented if the requested comparison is not implemented
540 any other false value if the requested comparison is false
541 any other true value if the requested comparison is true
542
543 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
544 NotImplemented.
545
546 (*) Practical amendments:
547
548 - If rich comparison returns NotImplemented, == and != are decided by
549 comparing the object pointer (i.e. falling back to the base object
550 implementation).
551
552 - If three-way comparison is not implemented, it falls back on rich
553 comparison (but not the other way around!).
554
Guido van Rossuma4073002002-05-31 20:03:54 +0000555*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000556
557/* Forward */
558static PyObject *do_richcompare(PyObject *v, PyObject *w, int op);
559
560/* Perform a three-way comparison, raising TypeError if three-way comparison
561 is not supported. */
Guido van Rossuma4073002002-05-31 20:03:54 +0000562static int
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000563do_compare(PyObject *v, PyObject *w)
Guido van Rossuma4073002002-05-31 20:03:54 +0000564{
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000565 cmpfunc f;
566 int ok;
567
568 if (v->ob_type == w->ob_type &&
569 (f = v->ob_type->tp_compare) != NULL) {
570 return (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000571 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000572
573 /* Now try three-way compare before giving up. This is intentionally
574 elaborate; if you have a it will raise TypeError if it detects two
575 objects that aren't ordered with respect to each other. */
576 ok = PyObject_RichCompareBool(v, w, Py_LT);
577 if (ok < 0)
578 return -1; /* Error */
579 if (ok)
580 return -1; /* Less than */
581 ok = PyObject_RichCompareBool(v, w, Py_GT);
582 if (ok < 0)
583 return -1; /* Error */
584 if (ok)
585 return 1; /* Greater than */
586 ok = PyObject_RichCompareBool(v, w, Py_EQ);
587 if (ok < 0)
588 return -1; /* Error */
589 if (ok)
590 return 0; /* Equal */
591
592 /* Give up */
593 PyErr_Format(PyExc_TypeError,
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000594 "unorderable types: '%.100s' != '%.100s'",
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000595 v->ob_type->tp_name,
596 w->ob_type->tp_name);
597 return -1;
Guido van Rossuma4073002002-05-31 20:03:54 +0000598}
599
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000600/* Perform a three-way comparison. This wraps do_compare() with a check for
601 NULL arguments and a recursion check. */
602int
603PyObject_Compare(PyObject *v, PyObject *w)
604{
605 int res;
Guido van Rossuma4073002002-05-31 20:03:54 +0000606
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000607 if (v == NULL || w == NULL) {
608 if (!PyErr_Occurred())
609 PyErr_BadInternalCall();
610 return -1;
611 }
612 if (Py_EnterRecursiveCall(" in cmp"))
613 return -1;
614 res = do_compare(v, w);
615 Py_LeaveRecursiveCall();
616 return res < 0 ? -1 : res;
617}
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000618
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000619/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000620int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000621
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000622static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000623
624/* Perform a rich comparison, raising TypeError when the requested comparison
625 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000626static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000627do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000628{
629 richcmpfunc f;
630 PyObject *res;
631
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000632 if (v->ob_type != w->ob_type &&
633 PyType_IsSubtype(w->ob_type, v->ob_type) &&
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000634 (f = w->ob_type->tp_richcompare) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000635 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000636 if (res != Py_NotImplemented)
637 return res;
638 Py_DECREF(res);
639 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000640 if ((f = v->ob_type->tp_richcompare) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000641 res = (*f)(v, w, op);
642 if (res != Py_NotImplemented)
643 return res;
644 Py_DECREF(res);
645 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000646 if ((f = w->ob_type->tp_richcompare) != NULL) {
647 res = (*f)(w, v, _Py_SwappedOp[op]);
648 if (res != Py_NotImplemented)
649 return res;
650 Py_DECREF(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000651 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000652 /* If neither object implements it, provide a sensible default
653 for == and !=, but raise an exception for ordering. */
654 switch (op) {
655 case Py_EQ:
656 res = (v == w) ? Py_True : Py_False;
657 break;
658 case Py_NE:
659 res = (v != w) ? Py_True : Py_False;
660 break;
661 default:
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000662 /* XXX Special-case None so it doesn't show as NoneType() */
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000663 PyErr_Format(PyExc_TypeError,
664 "unorderable types: %.100s() %s %.100s()",
665 v->ob_type->tp_name,
666 opstrings[op],
667 w->ob_type->tp_name);
668 return NULL;
669 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000670 Py_INCREF(res);
671 return res;
672}
673
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000674/* Perform a rich comparison with object result. This wraps do_richcompare()
675 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000676
Guido van Rossume797ec12001-01-17 15:24:28 +0000677PyObject *
678PyObject_RichCompare(PyObject *v, PyObject *w, int op)
679{
680 PyObject *res;
681
682 assert(Py_LT <= op && op <= Py_GE);
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000683 if (v == NULL || w == NULL) {
684 if (!PyErr_Occurred())
685 PyErr_BadInternalCall();
686 return NULL;
687 }
Armin Rigo2b3eb402003-10-28 12:05:48 +0000688 if (Py_EnterRecursiveCall(" in cmp"))
689 return NULL;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000690 res = do_richcompare(v, w, op);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000691 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000692 return res;
693}
694
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000695/* Perform a rich comparison with integer result. This wraps
696 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000697int
698PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
699{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000700 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000701 int ok;
702
Raymond Hettinger93d44812004-03-21 17:01:44 +0000703 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000704 if (res == NULL)
705 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000706 if (PyBool_Check(res))
707 ok = (res == Py_True);
708 else
709 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000710 Py_DECREF(res);
711 return ok;
712}
Fred Drake13634cf2000-06-29 19:17:04 +0000713
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000714/* Turn the result of a three-way comparison into the result expected by a
715 rich comparison. */
716PyObject *
717Py_CmpToRich(int op, int cmp)
718{
719 PyObject *res;
720 int ok;
721
722 if (PyErr_Occurred())
723 return NULL;
724 switch (op) {
725 case Py_LT:
726 ok = cmp < 0;
727 break;
728 case Py_LE:
729 ok = cmp <= 0;
730 break;
731 case Py_EQ:
732 ok = cmp == 0;
733 break;
734 case Py_NE:
735 ok = cmp != 0;
736 break;
737 case Py_GT:
738 ok = cmp > 0;
739 break;
740 case Py_GE:
741 ok = cmp >= 0;
742 break;
743 default:
744 PyErr_BadArgument();
745 return NULL;
746 }
747 res = ok ? Py_True : Py_False;
748 Py_INCREF(res);
749 return res;
750}
751
Fred Drake13634cf2000-06-29 19:17:04 +0000752/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000753 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000754
755 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
756*/
757
758long
Fred Drake100814d2000-07-09 15:48:49 +0000759_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000760{
Tim Peters39dce292000-08-15 03:34:48 +0000761 double intpart, fractpart;
762 int expo;
763 long hipart;
764 long x; /* the final hash value */
765 /* This is designed so that Python numbers of different types
766 * that compare equal hash to the same value; otherwise comparisons
767 * of mapping keys will turn out weird.
768 */
769
Tim Peters39dce292000-08-15 03:34:48 +0000770 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000771 if (fractpart == 0.0) {
772 /* This must return the same hash as an equal int or long. */
773 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
774 /* Convert to long and use its hash. */
775 PyObject *plong; /* converted to Python long */
776 if (Py_IS_INFINITY(intpart))
777 /* can't convert to long int -- arbitrary */
778 v = v < 0 ? -271828.0 : 314159.0;
779 plong = PyLong_FromDouble(v);
780 if (plong == NULL)
781 return -1;
782 x = PyObject_Hash(plong);
783 Py_DECREF(plong);
784 return x;
785 }
786 /* Fits in a C long == a Python int, so is its own hash. */
787 x = (long)intpart;
788 if (x == -1)
789 x = -2;
790 return x;
791 }
792 /* The fractional part is non-zero, so we don't have to worry about
793 * making this match the hash of some other type.
794 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000795 * Since the VAX D double format has 56 mantissa bits, which is the
796 * most of any double format in use, each of these parts may have as
797 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000798 * So, assuming sizeof(long) >= 4, each part can be broken into two
799 * longs; frexp and multiplication are used to do that.
800 * Also, since the Cray double format has 15 exponent bits, which is
801 * the most of any double format in use, shifting the exponent field
802 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000803 */
Tim Peters39dce292000-08-15 03:34:48 +0000804 v = frexp(v, &expo);
805 v *= 2147483648.0; /* 2**31 */
806 hipart = (long)v; /* take the top 32 bits */
807 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
808 x = hipart + (long)v + (expo << 15);
809 if (x == -1)
810 x = -2;
811 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000812}
813
814long
Fred Drake100814d2000-07-09 15:48:49 +0000815_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000816{
817#if SIZEOF_LONG >= SIZEOF_VOID_P
818 return (long)p;
819#else
820 /* convert to a Python long and hash that */
821 PyObject* longobj;
822 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000823
Fred Drake13634cf2000-06-29 19:17:04 +0000824 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
825 x = -1;
826 goto finally;
827 }
828 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000829
Fred Drake13634cf2000-06-29 19:17:04 +0000830finally:
831 Py_XDECREF(longobj);
832 return x;
833#endif
834}
835
836
Guido van Rossum9bfef441993-03-29 10:43:31 +0000837long
Fred Drake100814d2000-07-09 15:48:49 +0000838PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000839{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000840 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000841 if (tp->tp_hash != NULL)
842 return (*tp->tp_hash)(v);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000843 /* Otherwise, the object can't be hashed */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000844 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
845 v->ob_type->tp_name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000846 return -1;
847}
848
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000849PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000850PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000851{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000852 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000853
Tim Peters6d6c1a32001-08-02 04:15:00 +0000854 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000855 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000856 w = PyString_InternFromString(name);
857 if (w == NULL)
858 return NULL;
859 res = PyObject_GetAttr(v, w);
860 Py_XDECREF(w);
861 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000862}
863
864int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000865PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000866{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000867 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000868 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000869 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000870 return 1;
871 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000872 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000873 return 0;
874}
875
876int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000877PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000878{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879 PyObject *s;
880 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000881
Tim Peters6d6c1a32001-08-02 04:15:00 +0000882 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000883 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884 s = PyString_InternFromString(name);
885 if (s == NULL)
886 return -1;
887 res = PyObject_SetAttr(v, s, w);
888 Py_XDECREF(s);
889 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000890}
891
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000892PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000893PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000894{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895 PyTypeObject *tp = v->ob_type;
896
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000897 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000898#ifdef Py_USING_UNICODE
899 /* The Unicode to string conversion is done here because the
900 existing tp_getattro slots expect a string object as name
901 and we wouldn't want to break those. */
902 if (PyUnicode_Check(name)) {
903 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
904 if (name == NULL)
905 return NULL;
906 }
907 else
908#endif
909 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910 PyErr_Format(PyExc_TypeError,
911 "attribute name must be string, not '%.200s'",
912 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000913 return NULL;
914 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000915 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000916 if (tp->tp_getattro != NULL)
917 return (*tp->tp_getattro)(v, name);
918 if (tp->tp_getattr != NULL)
919 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
920 PyErr_Format(PyExc_AttributeError,
921 "'%.50s' object has no attribute '%.400s'",
922 tp->tp_name, PyString_AS_STRING(name));
923 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000924}
925
926int
Fred Drake100814d2000-07-09 15:48:49 +0000927PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000928{
929 PyObject *res = PyObject_GetAttr(v, name);
930 if (res != NULL) {
931 Py_DECREF(res);
932 return 1;
933 }
934 PyErr_Clear();
935 return 0;
936}
937
938int
Fred Drake100814d2000-07-09 15:48:49 +0000939PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000940{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000941 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000942 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000943
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000944 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000945#ifdef Py_USING_UNICODE
946 /* The Unicode to string conversion is done here because the
947 existing tp_setattro slots expect a string object as name
948 and we wouldn't want to break those. */
949 if (PyUnicode_Check(name)) {
950 name = PyUnicode_AsEncodedString(name, NULL, NULL);
951 if (name == NULL)
952 return -1;
953 }
Tim Peters803526b2002-07-07 05:13:56 +0000954 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000955#endif
956 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000957 PyErr_Format(PyExc_TypeError,
958 "attribute name must be string, not '%.200s'",
959 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000960 return -1;
961 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000962 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000963 else
964 Py_INCREF(name);
965
966 PyString_InternInPlace(&name);
967 if (tp->tp_setattro != NULL) {
968 err = (*tp->tp_setattro)(v, name, value);
969 Py_DECREF(name);
970 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000971 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000972 if (tp->tp_setattr != NULL) {
973 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
974 Py_DECREF(name);
975 return err;
976 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000977 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
979 PyErr_Format(PyExc_TypeError,
980 "'%.100s' object has no attributes "
981 "(%s .%.100s)",
982 tp->tp_name,
983 value==NULL ? "del" : "assign to",
984 PyString_AS_STRING(name));
985 else
986 PyErr_Format(PyExc_TypeError,
987 "'%.100s' object has only read-only attributes "
988 "(%s .%.100s)",
989 tp->tp_name,
990 value==NULL ? "del" : "assign to",
991 PyString_AS_STRING(name));
992 return -1;
993}
994
995/* Helper to get a pointer to an object's __dict__ slot, if any */
996
997PyObject **
998_PyObject_GetDictPtr(PyObject *obj)
999{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001000 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 PyTypeObject *tp = obj->ob_type;
1002
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 dictoffset = tp->tp_dictoffset;
1004 if (dictoffset == 0)
1005 return NULL;
1006 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001007 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001008 size_t size;
1009
1010 tsize = ((PyVarObject *)obj)->ob_size;
1011 if (tsize < 0)
1012 tsize = -tsize;
1013 size = _PyObject_VAR_SIZE(tp, tsize);
1014
Tim Peters6d483d32001-10-06 21:27:34 +00001015 dictoffset += (long)size;
1016 assert(dictoffset > 0);
1017 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018 }
1019 return (PyObject **) ((char *)obj + dictoffset);
1020}
1021
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001023PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001024{
1025 Py_INCREF(obj);
1026 return obj;
1027}
1028
Michael W. Hudson1593f502004-09-14 17:09:47 +00001029/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1030
Raymond Hettinger01538262003-03-17 08:24:35 +00001031PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1033{
1034 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001035 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001036 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001038 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039 PyObject **dictptr;
1040
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001041 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001042#ifdef Py_USING_UNICODE
1043 /* The Unicode to string conversion is done here because the
1044 existing tp_setattro slots expect a string object as name
1045 and we wouldn't want to break those. */
1046 if (PyUnicode_Check(name)) {
1047 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1048 if (name == NULL)
1049 return NULL;
1050 }
Tim Peters803526b2002-07-07 05:13:56 +00001051 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001052#endif
1053 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001054 PyErr_Format(PyExc_TypeError,
1055 "attribute name must be string, not '%.200s'",
1056 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001057 return NULL;
1058 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001059 }
1060 else
1061 Py_INCREF(name);
1062
Tim Peters6d6c1a32001-08-02 04:15:00 +00001063 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001064 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001065 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 }
1067
Guido van Rossum056fbf42002-08-19 19:22:50 +00001068 /* Inline _PyType_Lookup */
1069 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001070 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001071 PyObject *mro, *base, *dict;
1072
1073 /* Look in tp_dict of types in MRO */
1074 mro = tp->tp_mro;
1075 assert(mro != NULL);
1076 assert(PyTuple_Check(mro));
1077 n = PyTuple_GET_SIZE(mro);
1078 for (i = 0; i < n; i++) {
1079 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001080 assert(PyType_Check(base));
1081 dict = ((PyTypeObject *)base)->tp_dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001082 assert(dict && PyDict_Check(dict));
1083 descr = PyDict_GetItem(dict, name);
1084 if (descr != NULL)
1085 break;
1086 }
1087 }
1088
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001089 Py_XINCREF(descr);
1090
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001092 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001093 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001094 if (f != NULL && PyDescr_IsData(descr)) {
1095 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001096 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001097 goto done;
1098 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 }
1100
Guido van Rossumc66ff442002-08-19 16:50:48 +00001101 /* Inline _PyObject_GetDictPtr */
1102 dictoffset = tp->tp_dictoffset;
1103 if (dictoffset != 0) {
1104 PyObject *dict;
1105 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001107 size_t size;
1108
1109 tsize = ((PyVarObject *)obj)->ob_size;
1110 if (tsize < 0)
1111 tsize = -tsize;
1112 size = _PyObject_VAR_SIZE(tp, tsize);
1113
1114 dictoffset += (long)size;
1115 assert(dictoffset > 0);
1116 assert(dictoffset % SIZEOF_VOID_P == 0);
1117 }
1118 dictptr = (PyObject **) ((char *)obj + dictoffset);
1119 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001121 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 if (res != NULL) {
1123 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001124 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001125 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 }
1127 }
1128 }
1129
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001130 if (f != NULL) {
1131 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001132 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001133 goto done;
1134 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135
1136 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001137 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001138 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001139 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001140 }
1141
1142 PyErr_Format(PyExc_AttributeError,
1143 "'%.50s' object has no attribute '%.400s'",
1144 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001145 done:
1146 Py_DECREF(name);
1147 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148}
1149
1150int
1151PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1152{
1153 PyTypeObject *tp = obj->ob_type;
1154 PyObject *descr;
1155 descrsetfunc f;
1156 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001157 int res = -1;
1158
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001159 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001160#ifdef Py_USING_UNICODE
1161 /* The Unicode to string conversion is done here because the
1162 existing tp_setattro slots expect a string object as name
1163 and we wouldn't want to break those. */
1164 if (PyUnicode_Check(name)) {
1165 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1166 if (name == NULL)
1167 return -1;
1168 }
Tim Peters803526b2002-07-07 05:13:56 +00001169 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001170#endif
1171 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001172 PyErr_Format(PyExc_TypeError,
1173 "attribute name must be string, not '%.200s'",
1174 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001175 return -1;
1176 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001177 }
1178 else
1179 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180
1181 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001182 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001183 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184 }
1185
1186 descr = _PyType_Lookup(tp, name);
1187 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001188 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001190 if (f != NULL && PyDescr_IsData(descr)) {
1191 res = f(descr, obj, value);
1192 goto done;
1193 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001194 }
1195
1196 dictptr = _PyObject_GetDictPtr(obj);
1197 if (dictptr != NULL) {
1198 PyObject *dict = *dictptr;
1199 if (dict == NULL && value != NULL) {
1200 dict = PyDict_New();
1201 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001202 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 *dictptr = dict;
1204 }
1205 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001206 if (value == NULL)
1207 res = PyDict_DelItem(dict, name);
1208 else
1209 res = PyDict_SetItem(dict, name, value);
1210 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1211 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001212 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 }
1214 }
1215
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001216 if (f != NULL) {
1217 res = f(descr, obj, value);
1218 goto done;
1219 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220
1221 if (descr == NULL) {
1222 PyErr_Format(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001223 "'%.100s' object has no attribute '%.200s'",
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001225 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001226 }
1227
1228 PyErr_Format(PyExc_AttributeError,
1229 "'%.50s' object attribute '%.400s' is read-only",
1230 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001231 done:
1232 Py_DECREF(name);
1233 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001234}
1235
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001236/* Test a value used as condition, e.g., in a for or if statement.
1237 Return -1 if an error occurred */
1238
1239int
Fred Drake100814d2000-07-09 15:48:49 +00001240PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001241{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001242 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001243 if (v == Py_True)
1244 return 1;
1245 if (v == Py_False)
1246 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001247 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001248 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001249 else if (v->ob_type->tp_as_number != NULL &&
Jack Diederich4dafcc42006-11-28 19:15:13 +00001250 v->ob_type->tp_as_number->nb_bool != NULL)
1251 res = (*v->ob_type->tp_as_number->nb_bool)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001252 else if (v->ob_type->tp_as_mapping != NULL &&
1253 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001254 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001255 else if (v->ob_type->tp_as_sequence != NULL &&
1256 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001257 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1258 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001259 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001260 /* if it is negative, it should be either -1 or -2 */
1261 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001262}
1263
Tim Peters803526b2002-07-07 05:13:56 +00001264/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001265 Return -1 if an error occurred */
1266
1267int
Fred Drake100814d2000-07-09 15:48:49 +00001268PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001269{
1270 int res;
1271 res = PyObject_IsTrue(v);
1272 if (res < 0)
1273 return res;
1274 return res == 0;
1275}
1276
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001277/* Test whether an object can be called */
1278
1279int
Fred Drake100814d2000-07-09 15:48:49 +00001280PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001281{
1282 if (x == NULL)
1283 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001284 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001285}
1286
Georg Brandle32b4222007-03-10 22:13:27 +00001287/* ------------------------- PyObject_Dir() helpers ------------------------- */
1288
Tim Peters7eea37e2001-09-04 22:08:56 +00001289/* Helper for PyObject_Dir.
1290 Merge the __dict__ of aclass into dict, and recursively also all
1291 the __dict__s of aclass's base classes. The order of merging isn't
1292 defined, as it's expected that only the final set of dict keys is
1293 interesting.
1294 Return 0 on success, -1 on error.
1295*/
1296
1297static int
1298merge_class_dict(PyObject* dict, PyObject* aclass)
1299{
1300 PyObject *classdict;
1301 PyObject *bases;
1302
1303 assert(PyDict_Check(dict));
1304 assert(aclass);
1305
1306 /* Merge in the type's dict (if any). */
1307 classdict = PyObject_GetAttrString(aclass, "__dict__");
1308 if (classdict == NULL)
1309 PyErr_Clear();
1310 else {
1311 int status = PyDict_Update(dict, classdict);
1312 Py_DECREF(classdict);
1313 if (status < 0)
1314 return -1;
1315 }
1316
1317 /* Recursively merge in the base types' (if any) dicts. */
1318 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001319 if (bases == NULL)
1320 PyErr_Clear();
1321 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001322 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001323 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001324 n = PySequence_Size(bases); /* This better be right */
1325 if (n < 0)
1326 PyErr_Clear();
1327 else {
1328 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001329 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001330 PyObject *base = PySequence_GetItem(bases, i);
1331 if (base == NULL) {
1332 Py_DECREF(bases);
1333 return -1;
1334 }
Tim Peters18e70832003-02-05 19:35:19 +00001335 status = merge_class_dict(dict, base);
1336 Py_DECREF(base);
1337 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001338 Py_DECREF(bases);
1339 return -1;
1340 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001341 }
1342 }
1343 Py_DECREF(bases);
1344 }
1345 return 0;
1346}
1347
Georg Brandle32b4222007-03-10 22:13:27 +00001348/* Helper for PyObject_Dir without arguments: returns the local scope. */
1349static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001350_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001351{
Georg Brandled3b8382007-03-12 13:15:14 +00001352 PyObject *names;
Georg Brandle32b4222007-03-10 22:13:27 +00001353 PyObject *locals = PyEval_GetLocals();
Tim Peters305b5852001-09-17 02:38:46 +00001354
Georg Brandle32b4222007-03-10 22:13:27 +00001355 if (locals == NULL) {
1356 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1357 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001358 }
1359
Georg Brandled3b8382007-03-12 13:15:14 +00001360 names = PyMapping_Keys(locals);
1361 if (!names)
1362 return NULL;
1363 if (!PyList_Check(names)) {
1364 PyErr_Format(PyExc_TypeError,
1365 "dir(): expected keys() of locals to be a list, "
1366 "not '%.200s'", names->ob_type->tp_name);
1367 Py_DECREF(names);
1368 return NULL;
1369 }
Georg Brandle32b4222007-03-10 22:13:27 +00001370 /* the locals don't need to be DECREF'd */
Georg Brandled3b8382007-03-12 13:15:14 +00001371 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001372}
1373
1374/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
1375 We deliberately don't suck up its __class__, as methods belonging to the
1376 metaclass would probably be more confusing than helpful.
1377*/
1378static PyObject *
1379_specialized_dir_type(PyObject *obj)
1380{
1381 PyObject *result = NULL;
1382 PyObject *dict = PyDict_New();
1383
1384 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1385 result = PyDict_Keys(dict);
1386
1387 Py_XDECREF(dict);
Tim Peters305b5852001-09-17 02:38:46 +00001388 return result;
1389}
1390
Georg Brandle32b4222007-03-10 22:13:27 +00001391/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1392static PyObject *
1393_specialized_dir_module(PyObject *obj)
Tim Peters7eea37e2001-09-04 22:08:56 +00001394{
Georg Brandle32b4222007-03-10 22:13:27 +00001395 PyObject *result = NULL;
1396 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Tim Peters7eea37e2001-09-04 22:08:56 +00001397
Georg Brandle32b4222007-03-10 22:13:27 +00001398 if (dict != NULL) {
1399 if (PyDict_Check(dict))
1400 result = PyDict_Keys(dict);
1401 else {
1402 PyErr_Format(PyExc_TypeError,
1403 "%.200s.__dict__ is not a dictionary",
1404 PyModule_GetName(obj));
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001405 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001406 }
1407
Georg Brandle32b4222007-03-10 22:13:27 +00001408 Py_XDECREF(dict);
1409 return result;
1410}
Tim Peters7eea37e2001-09-04 22:08:56 +00001411
Georg Brandle32b4222007-03-10 22:13:27 +00001412/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1413 and recursively up the __class__.__bases__ chain.
1414*/
1415static PyObject *
1416_generic_dir(PyObject *obj)
1417{
1418 PyObject *result = NULL;
1419 PyObject *dict = NULL;
1420 PyObject *itsclass = NULL;
1421
1422 /* Get __dict__ (which may or may not be a real dict...) */
1423 dict = PyObject_GetAttrString(obj, "__dict__");
1424 if (dict == NULL) {
1425 PyErr_Clear();
1426 dict = PyDict_New();
1427 }
1428 else if (!PyDict_Check(dict)) {
1429 Py_DECREF(dict);
1430 dict = PyDict_New();
1431 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001432 else {
Georg Brandle32b4222007-03-10 22:13:27 +00001433 /* Copy __dict__ to avoid mutating it. */
1434 PyObject *temp = PyDict_Copy(dict);
1435 Py_DECREF(dict);
1436 dict = temp;
Tim Peters7eea37e2001-09-04 22:08:56 +00001437 }
1438
Georg Brandle32b4222007-03-10 22:13:27 +00001439 if (dict == NULL)
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001440 goto error;
Tim Peters7eea37e2001-09-04 22:08:56 +00001441
Georg Brandle32b4222007-03-10 22:13:27 +00001442 /* Merge in attrs reachable from its class. */
1443 itsclass = PyObject_GetAttrString(obj, "__class__");
1444 if (itsclass == NULL)
1445 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1446 __class__ exists? */
1447 PyErr_Clear();
1448 else {
1449 if (merge_class_dict(dict, itsclass) != 0)
1450 goto error;
1451 }
1452
1453 result = PyDict_Keys(dict);
Tim Peters7eea37e2001-09-04 22:08:56 +00001454 /* fall through */
Georg Brandle32b4222007-03-10 22:13:27 +00001455error:
1456 Py_XDECREF(itsclass);
1457 Py_XDECREF(dict);
1458 return result;
1459}
1460
1461/* Helper for PyObject_Dir: object introspection.
1462 This calls one of the above specialized versions if no __dir__ method
1463 exists. */
1464static PyObject *
1465_dir_object(PyObject *obj)
1466{
1467 PyObject * result = NULL;
1468 PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type,
1469 "__dir__");
1470
1471 assert(obj);
1472 if (dirfunc == NULL) {
1473 /* use default implementation */
1474 PyErr_Clear();
1475 if (PyModule_Check(obj))
1476 result = _specialized_dir_module(obj);
1477 else if (PyType_Check(obj))
1478 result = _specialized_dir_type(obj);
1479 else
1480 result = _generic_dir(obj);
1481 }
1482 else {
1483 /* use __dir__ */
1484 result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
1485 Py_DECREF(dirfunc);
1486 if (result == NULL)
1487 return NULL;
1488
1489 /* result must be a list */
1490 /* XXX(gbrandl): could also check if all items are strings */
1491 if (!PyList_Check(result)) {
1492 PyErr_Format(PyExc_TypeError,
1493 "__dir__() must return a list, not %.200s",
1494 result->ob_type->tp_name);
1495 Py_DECREF(result);
1496 result = NULL;
1497 }
1498 }
1499
1500 return result;
1501}
1502
1503/* Implementation of dir() -- if obj is NULL, returns the names in the current
1504 (local) scope. Otherwise, performs introspection of the object: returns a
1505 sorted list of attribute names (supposedly) accessible from the object
1506*/
1507PyObject *
1508PyObject_Dir(PyObject *obj)
1509{
1510 PyObject * result;
1511
1512 if (obj == NULL)
1513 /* no object -- introspect the locals */
1514 result = _dir_locals();
1515 else
1516 /* object -- introspect the object */
1517 result = _dir_object(obj);
1518
1519 assert(result == NULL || PyList_Check(result));
1520
1521 if (result != NULL && PyList_Sort(result) != 0) {
1522 /* sorting the list failed */
1523 Py_DECREF(result);
1524 result = NULL;
1525 }
1526
Tim Peters7eea37e2001-09-04 22:08:56 +00001527 return result;
1528}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001529
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530/*
1531NoObject is usable as a non-NULL undefined value, used by the macro None.
1532There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001533so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001534(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001535*/
1536
Guido van Rossum0c182a11992-03-27 17:26:13 +00001537/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001538static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001539none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001540{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001541 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001542}
1543
Barry Warsaw9bf16442001-01-23 16:24:35 +00001544/* ARGUSED */
1545static void
Tim Peters803526b2002-07-07 05:13:56 +00001546none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001547{
1548 /* This should never get called, but we also don't want to SEGV if
1549 * we accidently decref None out of existance.
1550 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001551 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001552}
1553
1554
Guido van Rossumba21a492001-08-16 08:17:26 +00001555static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001556 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001557 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001558 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001559 0,
1560 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001561 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001562 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001563 0, /*tp_getattr*/
1564 0, /*tp_setattr*/
1565 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001566 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001567 0, /*tp_as_number*/
1568 0, /*tp_as_sequence*/
1569 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001570 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001571};
1572
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001573PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001574 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001575};
1576
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001577/* NotImplemented is an object that can be used to signal that an
1578 operation is not implemented for the given type combination. */
1579
1580static PyObject *
1581NotImplemented_repr(PyObject *op)
1582{
1583 return PyString_FromString("NotImplemented");
1584}
1585
1586static PyTypeObject PyNotImplemented_Type = {
1587 PyObject_HEAD_INIT(&PyType_Type)
1588 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001589 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001590 0,
1591 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001592 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001593 0, /*tp_print*/
1594 0, /*tp_getattr*/
1595 0, /*tp_setattr*/
1596 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001597 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001598 0, /*tp_as_number*/
1599 0, /*tp_as_sequence*/
1600 0, /*tp_as_mapping*/
1601 0, /*tp_hash */
1602};
1603
1604PyObject _Py_NotImplementedStruct = {
1605 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1606};
1607
Guido van Rossumba21a492001-08-16 08:17:26 +00001608void
1609_Py_ReadyTypes(void)
1610{
1611 if (PyType_Ready(&PyType_Type) < 0)
1612 Py_FatalError("Can't initialize 'type'");
1613
Fred Drake0a4dd392004-07-02 18:57:45 +00001614 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1615 Py_FatalError("Can't initialize 'weakref'");
1616
Guido van Rossum77f6a652002-04-03 22:41:51 +00001617 if (PyType_Ready(&PyBool_Type) < 0)
1618 Py_FatalError("Can't initialize 'bool'");
1619
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001620 if (PyType_Ready(&PyBytes_Type) < 0)
1621 Py_FatalError("Can't initialize 'bytes'");
1622
Guido van Rossumcacfc072002-05-24 19:01:59 +00001623 if (PyType_Ready(&PyString_Type) < 0)
1624 Py_FatalError("Can't initialize 'str'");
1625
Guido van Rossumba21a492001-08-16 08:17:26 +00001626 if (PyType_Ready(&PyList_Type) < 0)
1627 Py_FatalError("Can't initialize 'list'");
1628
1629 if (PyType_Ready(&PyNone_Type) < 0)
1630 Py_FatalError("Can't initialize type(None)");
1631
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001632 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1633 Py_FatalError("Can't initialize type(Ellipsis)");
1634
Guido van Rossumba21a492001-08-16 08:17:26 +00001635 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1636 Py_FatalError("Can't initialize type(NotImplemented)");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001637
1638 if (PyType_Ready(&PyCode_Type) < 0)
1639 Py_FatalError("Can't initialize 'code'");
Guido van Rossumba21a492001-08-16 08:17:26 +00001640}
1641
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001642
Guido van Rossum84a90321996-05-22 16:34:47 +00001643#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001644
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001645void
Fred Drake100814d2000-07-09 15:48:49 +00001646_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001647{
Tim Peters34592512002-07-11 06:23:50 +00001648 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001649 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001650 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001651 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001652}
1653
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001654void
Fred Drake100814d2000-07-09 15:48:49 +00001655_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001656{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001657#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001658 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001659#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001660 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001661 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001662 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001663 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001664 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001665#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001666 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1667 if (p == op)
1668 break;
1669 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001670 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001671 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001672#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001673 op->_ob_next->_ob_prev = op->_ob_prev;
1674 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001675 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001676 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001677}
1678
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001679void
Fred Drake100814d2000-07-09 15:48:49 +00001680_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001681{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001682 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001683 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001684 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001685}
1686
Tim Peters269b2a62003-04-17 19:52:29 +00001687/* Print all live objects. Because PyObject_Print is called, the
1688 * interpreter must be in a healthy state.
1689 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001690void
Fred Drake100814d2000-07-09 15:48:49 +00001691_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001692{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001693 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001694 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001695 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001696 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001697 if (PyObject_Print(op, fp, 0) != 0)
1698 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001699 putc('\n', fp);
1700 }
1701}
1702
Tim Peters269b2a62003-04-17 19:52:29 +00001703/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1704 * doesn't make any calls to the Python C API, so is always safe to call.
1705 */
1706void
1707_Py_PrintReferenceAddresses(FILE *fp)
1708{
1709 PyObject *op;
1710 fprintf(fp, "Remaining object addresses:\n");
1711 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001712 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1713 op->ob_refcnt, op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001714}
1715
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001716PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001717_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001718{
1719 int i, n;
1720 PyObject *t = NULL;
1721 PyObject *res, *op;
1722
1723 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1724 return NULL;
1725 op = refchain._ob_next;
1726 res = PyList_New(0);
1727 if (res == NULL)
1728 return NULL;
1729 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1730 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001731 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001732 op = op->_ob_next;
1733 if (op == &refchain)
1734 return res;
1735 }
1736 if (PyList_Append(res, op) < 0) {
1737 Py_DECREF(res);
1738 return NULL;
1739 }
1740 op = op->_ob_next;
1741 }
1742 return res;
1743}
1744
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001745#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001746
1747
1748/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001749PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001750
1751
1752/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001753Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001754
1755
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001756/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001757
Thomas Wouters334fb892000-07-25 12:56:38 +00001758void *
Fred Drake100814d2000-07-09 15:48:49 +00001759PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001760{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001761 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001762}
1763
Thomas Wouters334fb892000-07-25 12:56:38 +00001764void *
1765PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001766{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001767 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001768}
1769
1770void
Thomas Wouters334fb892000-07-25 12:56:38 +00001771PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001772{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001773 PyMem_FREE(p);
1774}
1775
1776
Guido van Rossum86610361998-04-10 22:32:46 +00001777/* These methods are used to control infinite recursion in repr, str, print,
1778 etc. Container objects that may recursively contain themselves,
1779 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1780 Py_ReprLeave() to avoid infinite recursion.
1781
1782 Py_ReprEnter() returns 0 the first time it is called for a particular
1783 object and 1 every time thereafter. It returns -1 if an exception
1784 occurred. Py_ReprLeave() has no return value.
1785
1786 See dictobject.c and listobject.c for examples of use.
1787*/
1788
1789#define KEY "Py_Repr"
1790
1791int
Fred Drake100814d2000-07-09 15:48:49 +00001792Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001793{
1794 PyObject *dict;
1795 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001796 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001797
1798 dict = PyThreadState_GetDict();
1799 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001800 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001801 list = PyDict_GetItemString(dict, KEY);
1802 if (list == NULL) {
1803 list = PyList_New(0);
1804 if (list == NULL)
1805 return -1;
1806 if (PyDict_SetItemString(dict, KEY, list) < 0)
1807 return -1;
1808 Py_DECREF(list);
1809 }
1810 i = PyList_GET_SIZE(list);
1811 while (--i >= 0) {
1812 if (PyList_GET_ITEM(list, i) == obj)
1813 return 1;
1814 }
1815 PyList_Append(list, obj);
1816 return 0;
1817}
1818
1819void
Fred Drake100814d2000-07-09 15:48:49 +00001820Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001821{
1822 PyObject *dict;
1823 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001824 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001825
1826 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001827 if (dict == NULL)
1828 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001829 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001830 if (list == NULL || !PyList_Check(list))
1831 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001832 i = PyList_GET_SIZE(list);
1833 /* Count backwards because we always expect obj to be list[-1] */
1834 while (--i >= 0) {
1835 if (PyList_GET_ITEM(list, i) == obj) {
1836 PyList_SetSlice(list, i, i + 1, NULL);
1837 break;
1838 }
1839 }
1840}
Guido van Rossumd724b232000-03-13 16:01:29 +00001841
Tim Peters803526b2002-07-07 05:13:56 +00001842/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001843
Tim Peters803526b2002-07-07 05:13:56 +00001844/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001845int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001846
Tim Peters803526b2002-07-07 05:13:56 +00001847/* List of objects that still need to be cleaned up, singly linked via their
1848 * gc headers' gc_prev pointers.
1849 */
1850PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001851
Tim Peters803526b2002-07-07 05:13:56 +00001852/* Add op to the _PyTrash_delete_later list. Called when the current
1853 * call-stack depth gets large. op must be a currently untracked gc'ed
1854 * object, with refcount 0. Py_DECREF must already have been called on it.
1855 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001856void
Fred Drake100814d2000-07-09 15:48:49 +00001857_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001858{
Tim Peters803526b2002-07-07 05:13:56 +00001859 assert(PyObject_IS_GC(op));
1860 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1861 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00001862 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001863 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001864}
1865
Tim Peters803526b2002-07-07 05:13:56 +00001866/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1867 * the call-stack unwinds again.
1868 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001869void
Fred Drake100814d2000-07-09 15:48:49 +00001870_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001871{
1872 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00001873 PyObject *op = _PyTrash_delete_later;
1874 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001875
Neil Schemenauerf589c052002-03-29 03:05:54 +00001876 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00001877 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001878
Tim Peters803526b2002-07-07 05:13:56 +00001879 /* Call the deallocator directly. This used to try to
1880 * fool Py_DECREF into calling it indirectly, but
1881 * Py_DECREF was already called on this object, and in
1882 * assorted non-release builds calling Py_DECREF again ends
1883 * up distorting allocation statistics.
1884 */
1885 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00001886 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00001887 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00001888 --_PyTrash_delete_nesting;
1889 }
1890}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001891
1892#ifdef __cplusplus
1893}
1894#endif