blob: 4fee2f02feb1e1abee7686183786ee126a050869 [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
317_Py_Break(void)
318{
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 Rossum47b9ff62006-08-24 00:41:19 +0000622static char *opstrings[] = {">", ">=", "==", "!=", "<", "<="};
623
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:
662 PyErr_Format(PyExc_TypeError,
663 "unorderable types: %.100s() %s %.100s()",
664 v->ob_type->tp_name,
665 opstrings[op],
666 w->ob_type->tp_name);
667 return NULL;
668 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000669 Py_INCREF(res);
670 return res;
671}
672
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000673/* Perform a rich comparison with object result. This wraps do_richcompare()
674 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000675
Guido van Rossume797ec12001-01-17 15:24:28 +0000676PyObject *
677PyObject_RichCompare(PyObject *v, PyObject *w, int op)
678{
679 PyObject *res;
680
681 assert(Py_LT <= op && op <= Py_GE);
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000682 if (v == NULL || w == NULL) {
683 if (!PyErr_Occurred())
684 PyErr_BadInternalCall();
685 return NULL;
686 }
Armin Rigo2b3eb402003-10-28 12:05:48 +0000687 if (Py_EnterRecursiveCall(" in cmp"))
688 return NULL;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000689 res = do_richcompare(v, w, op);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000690 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000691 return res;
692}
693
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000694/* Perform a rich comparison with integer result. This wraps
695 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000696int
697PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
698{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000699 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000700 int ok;
701
Raymond Hettinger93d44812004-03-21 17:01:44 +0000702 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000703 if (res == NULL)
704 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000705 if (PyBool_Check(res))
706 ok = (res == Py_True);
707 else
708 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000709 Py_DECREF(res);
710 return ok;
711}
Fred Drake13634cf2000-06-29 19:17:04 +0000712
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000713/* Turn the result of a three-way comparison into the result expected by a
714 rich comparison. */
715PyObject *
716Py_CmpToRich(int op, int cmp)
717{
718 PyObject *res;
719 int ok;
720
721 if (PyErr_Occurred())
722 return NULL;
723 switch (op) {
724 case Py_LT:
725 ok = cmp < 0;
726 break;
727 case Py_LE:
728 ok = cmp <= 0;
729 break;
730 case Py_EQ:
731 ok = cmp == 0;
732 break;
733 case Py_NE:
734 ok = cmp != 0;
735 break;
736 case Py_GT:
737 ok = cmp > 0;
738 break;
739 case Py_GE:
740 ok = cmp >= 0;
741 break;
742 default:
743 PyErr_BadArgument();
744 return NULL;
745 }
746 res = ok ? Py_True : Py_False;
747 Py_INCREF(res);
748 return res;
749}
750
Fred Drake13634cf2000-06-29 19:17:04 +0000751/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000752 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000753
754 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
755*/
756
757long
Fred Drake100814d2000-07-09 15:48:49 +0000758_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000759{
Tim Peters39dce292000-08-15 03:34:48 +0000760 double intpart, fractpart;
761 int expo;
762 long hipart;
763 long x; /* the final hash value */
764 /* This is designed so that Python numbers of different types
765 * that compare equal hash to the same value; otherwise comparisons
766 * of mapping keys will turn out weird.
767 */
768
Tim Peters39dce292000-08-15 03:34:48 +0000769 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000770 if (fractpart == 0.0) {
771 /* This must return the same hash as an equal int or long. */
772 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
773 /* Convert to long and use its hash. */
774 PyObject *plong; /* converted to Python long */
775 if (Py_IS_INFINITY(intpart))
776 /* can't convert to long int -- arbitrary */
777 v = v < 0 ? -271828.0 : 314159.0;
778 plong = PyLong_FromDouble(v);
779 if (plong == NULL)
780 return -1;
781 x = PyObject_Hash(plong);
782 Py_DECREF(plong);
783 return x;
784 }
785 /* Fits in a C long == a Python int, so is its own hash. */
786 x = (long)intpart;
787 if (x == -1)
788 x = -2;
789 return x;
790 }
791 /* The fractional part is non-zero, so we don't have to worry about
792 * making this match the hash of some other type.
793 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000794 * Since the VAX D double format has 56 mantissa bits, which is the
795 * most of any double format in use, each of these parts may have as
796 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000797 * So, assuming sizeof(long) >= 4, each part can be broken into two
798 * longs; frexp and multiplication are used to do that.
799 * Also, since the Cray double format has 15 exponent bits, which is
800 * the most of any double format in use, shifting the exponent field
801 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000802 */
Tim Peters39dce292000-08-15 03:34:48 +0000803 v = frexp(v, &expo);
804 v *= 2147483648.0; /* 2**31 */
805 hipart = (long)v; /* take the top 32 bits */
806 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
807 x = hipart + (long)v + (expo << 15);
808 if (x == -1)
809 x = -2;
810 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000811}
812
813long
Fred Drake100814d2000-07-09 15:48:49 +0000814_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000815{
816#if SIZEOF_LONG >= SIZEOF_VOID_P
817 return (long)p;
818#else
819 /* convert to a Python long and hash that */
820 PyObject* longobj;
821 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000822
Fred Drake13634cf2000-06-29 19:17:04 +0000823 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
824 x = -1;
825 goto finally;
826 }
827 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000828
Fred Drake13634cf2000-06-29 19:17:04 +0000829finally:
830 Py_XDECREF(longobj);
831 return x;
832#endif
833}
834
835
Guido van Rossum9bfef441993-03-29 10:43:31 +0000836long
Fred Drake100814d2000-07-09 15:48:49 +0000837PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000838{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000839 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000840 if (tp->tp_hash != NULL)
841 return (*tp->tp_hash)(v);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000842 /* Otherwise, the object can't be hashed */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000843 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
844 v->ob_type->tp_name);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000845 return -1;
846}
847
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000848PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000849PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000850{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000852
Tim Peters6d6c1a32001-08-02 04:15:00 +0000853 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000854 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000855 w = PyString_InternFromString(name);
856 if (w == NULL)
857 return NULL;
858 res = PyObject_GetAttr(v, w);
859 Py_XDECREF(w);
860 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000861}
862
863int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000864PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000865{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000866 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000867 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000868 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000869 return 1;
870 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000871 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000872 return 0;
873}
874
875int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000876PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000877{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878 PyObject *s;
879 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000880
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +0000882 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000883 s = PyString_InternFromString(name);
884 if (s == NULL)
885 return -1;
886 res = PyObject_SetAttr(v, s, w);
887 Py_XDECREF(s);
888 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000889}
890
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000891PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000892PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000893{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000894 PyTypeObject *tp = v->ob_type;
895
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000896 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000897#ifdef Py_USING_UNICODE
898 /* The Unicode to string conversion is done here because the
899 existing tp_getattro slots expect a string object as name
900 and we wouldn't want to break those. */
901 if (PyUnicode_Check(name)) {
902 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
903 if (name == NULL)
904 return NULL;
905 }
906 else
907#endif
908 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000909 PyErr_Format(PyExc_TypeError,
910 "attribute name must be string, not '%.200s'",
911 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000912 return NULL;
913 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000914 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000915 if (tp->tp_getattro != NULL)
916 return (*tp->tp_getattro)(v, name);
917 if (tp->tp_getattr != NULL)
918 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
919 PyErr_Format(PyExc_AttributeError,
920 "'%.50s' object has no attribute '%.400s'",
921 tp->tp_name, PyString_AS_STRING(name));
922 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000923}
924
925int
Fred Drake100814d2000-07-09 15:48:49 +0000926PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000927{
928 PyObject *res = PyObject_GetAttr(v, name);
929 if (res != NULL) {
930 Py_DECREF(res);
931 return 1;
932 }
933 PyErr_Clear();
934 return 0;
935}
936
937int
Fred Drake100814d2000-07-09 15:48:49 +0000938PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000939{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000940 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000941 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000942
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000943 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000944#ifdef Py_USING_UNICODE
945 /* The Unicode to string conversion is done here because the
946 existing tp_setattro slots expect a string object as name
947 and we wouldn't want to break those. */
948 if (PyUnicode_Check(name)) {
949 name = PyUnicode_AsEncodedString(name, NULL, NULL);
950 if (name == NULL)
951 return -1;
952 }
Tim Peters803526b2002-07-07 05:13:56 +0000953 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000954#endif
955 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000956 PyErr_Format(PyExc_TypeError,
957 "attribute name must be string, not '%.200s'",
958 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +0000959 return -1;
960 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +0000961 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000962 else
963 Py_INCREF(name);
964
965 PyString_InternInPlace(&name);
966 if (tp->tp_setattro != NULL) {
967 err = (*tp->tp_setattro)(v, name, value);
968 Py_DECREF(name);
969 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000970 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971 if (tp->tp_setattr != NULL) {
972 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
973 Py_DECREF(name);
974 return err;
975 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000976 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
978 PyErr_Format(PyExc_TypeError,
979 "'%.100s' object has no attributes "
980 "(%s .%.100s)",
981 tp->tp_name,
982 value==NULL ? "del" : "assign to",
983 PyString_AS_STRING(name));
984 else
985 PyErr_Format(PyExc_TypeError,
986 "'%.100s' object has only read-only attributes "
987 "(%s .%.100s)",
988 tp->tp_name,
989 value==NULL ? "del" : "assign to",
990 PyString_AS_STRING(name));
991 return -1;
992}
993
994/* Helper to get a pointer to an object's __dict__ slot, if any */
995
996PyObject **
997_PyObject_GetDictPtr(PyObject *obj)
998{
Martin v. Löwis725507b2006-03-07 12:08:51 +0000999 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001000 PyTypeObject *tp = obj->ob_type;
1001
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002 dictoffset = tp->tp_dictoffset;
1003 if (dictoffset == 0)
1004 return NULL;
1005 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001006 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001007 size_t size;
1008
1009 tsize = ((PyVarObject *)obj)->ob_size;
1010 if (tsize < 0)
1011 tsize = -tsize;
1012 size = _PyObject_VAR_SIZE(tp, tsize);
1013
Tim Peters6d483d32001-10-06 21:27:34 +00001014 dictoffset += (long)size;
1015 assert(dictoffset > 0);
1016 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001017 }
1018 return (PyObject **) ((char *)obj + dictoffset);
1019}
1020
Tim Peters6d6c1a32001-08-02 04:15:00 +00001021PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001022PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001023{
1024 Py_INCREF(obj);
1025 return obj;
1026}
1027
Michael W. Hudson1593f502004-09-14 17:09:47 +00001028/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1029
Raymond Hettinger01538262003-03-17 08:24:35 +00001030PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1032{
1033 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001034 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001035 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001037 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038 PyObject **dictptr;
1039
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001040 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001041#ifdef Py_USING_UNICODE
1042 /* The Unicode to string conversion is done here because the
1043 existing tp_setattro slots expect a string object as name
1044 and we wouldn't want to break those. */
1045 if (PyUnicode_Check(name)) {
1046 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1047 if (name == NULL)
1048 return NULL;
1049 }
Tim Peters803526b2002-07-07 05:13:56 +00001050 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001051#endif
1052 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001053 PyErr_Format(PyExc_TypeError,
1054 "attribute name must be string, not '%.200s'",
1055 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001056 return NULL;
1057 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001058 }
1059 else
1060 Py_INCREF(name);
1061
Tim Peters6d6c1a32001-08-02 04:15:00 +00001062 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001063 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001064 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001065 }
1066
Guido van Rossum056fbf42002-08-19 19:22:50 +00001067 /* Inline _PyType_Lookup */
1068 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001069 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001070 PyObject *mro, *base, *dict;
1071
1072 /* Look in tp_dict of types in MRO */
1073 mro = tp->tp_mro;
1074 assert(mro != NULL);
1075 assert(PyTuple_Check(mro));
1076 n = PyTuple_GET_SIZE(mro);
1077 for (i = 0; i < n; i++) {
1078 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001079 assert(PyType_Check(base));
1080 dict = ((PyTypeObject *)base)->tp_dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001081 assert(dict && PyDict_Check(dict));
1082 descr = PyDict_GetItem(dict, name);
1083 if (descr != NULL)
1084 break;
1085 }
1086 }
1087
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001088 Py_XINCREF(descr);
1089
Tim Peters6d6c1a32001-08-02 04:15:00 +00001090 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001091 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001093 if (f != NULL && PyDescr_IsData(descr)) {
1094 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001095 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001096 goto done;
1097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098 }
1099
Guido van Rossumc66ff442002-08-19 16:50:48 +00001100 /* Inline _PyObject_GetDictPtr */
1101 dictoffset = tp->tp_dictoffset;
1102 if (dictoffset != 0) {
1103 PyObject *dict;
1104 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001105 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001106 size_t size;
1107
1108 tsize = ((PyVarObject *)obj)->ob_size;
1109 if (tsize < 0)
1110 tsize = -tsize;
1111 size = _PyObject_VAR_SIZE(tp, tsize);
1112
1113 dictoffset += (long)size;
1114 assert(dictoffset > 0);
1115 assert(dictoffset % SIZEOF_VOID_P == 0);
1116 }
1117 dictptr = (PyObject **) ((char *)obj + dictoffset);
1118 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001120 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 if (res != NULL) {
1122 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001123 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001124 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001125 }
1126 }
1127 }
1128
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001129 if (f != NULL) {
1130 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001131 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001132 goto done;
1133 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001134
1135 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001136 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001137 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001138 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139 }
1140
1141 PyErr_Format(PyExc_AttributeError,
1142 "'%.50s' object has no attribute '%.400s'",
1143 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001144 done:
1145 Py_DECREF(name);
1146 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147}
1148
1149int
1150PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1151{
1152 PyTypeObject *tp = obj->ob_type;
1153 PyObject *descr;
1154 descrsetfunc f;
1155 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001156 int res = -1;
1157
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001158 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001159#ifdef Py_USING_UNICODE
1160 /* The Unicode to string conversion is done here because the
1161 existing tp_setattro slots expect a string object as name
1162 and we wouldn't want to break those. */
1163 if (PyUnicode_Check(name)) {
1164 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1165 if (name == NULL)
1166 return -1;
1167 }
Tim Peters803526b2002-07-07 05:13:56 +00001168 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001169#endif
1170 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001171 PyErr_Format(PyExc_TypeError,
1172 "attribute name must be string, not '%.200s'",
1173 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001174 return -1;
1175 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001176 }
1177 else
1178 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179
1180 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001181 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001182 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 }
1184
1185 descr = _PyType_Lookup(tp, name);
1186 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001187 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001189 if (f != NULL && PyDescr_IsData(descr)) {
1190 res = f(descr, obj, value);
1191 goto done;
1192 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193 }
1194
1195 dictptr = _PyObject_GetDictPtr(obj);
1196 if (dictptr != NULL) {
1197 PyObject *dict = *dictptr;
1198 if (dict == NULL && value != NULL) {
1199 dict = PyDict_New();
1200 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001201 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001202 *dictptr = dict;
1203 }
1204 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205 if (value == NULL)
1206 res = PyDict_DelItem(dict, name);
1207 else
1208 res = PyDict_SetItem(dict, name, value);
1209 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1210 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001211 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212 }
1213 }
1214
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001215 if (f != NULL) {
1216 res = f(descr, obj, value);
1217 goto done;
1218 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219
1220 if (descr == NULL) {
1221 PyErr_Format(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001222 "'%.100s' object has no attribute '%.200s'",
Tim Peters6d6c1a32001-08-02 04:15:00 +00001223 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001224 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 }
1226
1227 PyErr_Format(PyExc_AttributeError,
1228 "'%.50s' object attribute '%.400s' is read-only",
1229 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001230 done:
1231 Py_DECREF(name);
1232 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001233}
1234
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001235/* Test a value used as condition, e.g., in a for or if statement.
1236 Return -1 if an error occurred */
1237
1238int
Fred Drake100814d2000-07-09 15:48:49 +00001239PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001240{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001241 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001242 if (v == Py_True)
1243 return 1;
1244 if (v == Py_False)
1245 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001246 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001247 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001248 else if (v->ob_type->tp_as_number != NULL &&
1249 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001250 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001251 else if (v->ob_type->tp_as_mapping != NULL &&
1252 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001253 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001254 else if (v->ob_type->tp_as_sequence != NULL &&
1255 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001256 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1257 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001258 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001259 /* if it is negative, it should be either -1 or -2 */
1260 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001261}
1262
Tim Peters803526b2002-07-07 05:13:56 +00001263/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001264 Return -1 if an error occurred */
1265
1266int
Fred Drake100814d2000-07-09 15:48:49 +00001267PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001268{
1269 int res;
1270 res = PyObject_IsTrue(v);
1271 if (res < 0)
1272 return res;
1273 return res == 0;
1274}
1275
Guido van Rossum5524a591995-01-10 15:26:20 +00001276/* Coerce two numeric types to the "larger" one.
1277 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001278 Return value:
1279 -1 if an error occurred;
1280 0 if the coercion succeeded (and then the reference counts are increased);
1281 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001282*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001283int
Fred Drake100814d2000-07-09 15:48:49 +00001284PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001285{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001286 register PyObject *v = *pv;
1287 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001288 int res;
1289
Guido van Rossum5524a591995-01-10 15:26:20 +00001290 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1291 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1292 if (res <= 0)
1293 return res;
1294 }
1295 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1296 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1297 if (res <= 0)
1298 return res;
1299 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001300 return 1;
1301}
1302
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001303/* Test whether an object can be called */
1304
1305int
Fred Drake100814d2000-07-09 15:48:49 +00001306PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001307{
1308 if (x == NULL)
1309 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001310 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001311}
1312
Tim Peters7eea37e2001-09-04 22:08:56 +00001313/* Helper for PyObject_Dir.
1314 Merge the __dict__ of aclass into dict, and recursively also all
1315 the __dict__s of aclass's base classes. The order of merging isn't
1316 defined, as it's expected that only the final set of dict keys is
1317 interesting.
1318 Return 0 on success, -1 on error.
1319*/
1320
1321static int
1322merge_class_dict(PyObject* dict, PyObject* aclass)
1323{
1324 PyObject *classdict;
1325 PyObject *bases;
1326
1327 assert(PyDict_Check(dict));
1328 assert(aclass);
1329
1330 /* Merge in the type's dict (if any). */
1331 classdict = PyObject_GetAttrString(aclass, "__dict__");
1332 if (classdict == NULL)
1333 PyErr_Clear();
1334 else {
1335 int status = PyDict_Update(dict, classdict);
1336 Py_DECREF(classdict);
1337 if (status < 0)
1338 return -1;
1339 }
1340
1341 /* Recursively merge in the base types' (if any) dicts. */
1342 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001343 if (bases == NULL)
1344 PyErr_Clear();
1345 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001346 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001347 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001348 n = PySequence_Size(bases); /* This better be right */
1349 if (n < 0)
1350 PyErr_Clear();
1351 else {
1352 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001353 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001354 PyObject *base = PySequence_GetItem(bases, i);
1355 if (base == NULL) {
1356 Py_DECREF(bases);
1357 return -1;
1358 }
Tim Peters18e70832003-02-05 19:35:19 +00001359 status = merge_class_dict(dict, base);
1360 Py_DECREF(base);
1361 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001362 Py_DECREF(bases);
1363 return -1;
1364 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001365 }
1366 }
1367 Py_DECREF(bases);
1368 }
1369 return 0;
1370}
1371
Tim Peters305b5852001-09-17 02:38:46 +00001372/* Helper for PyObject_Dir.
1373 If obj has an attr named attrname that's a list, merge its string
1374 elements into keys of dict.
1375 Return 0 on success, -1 on error. Errors due to not finding the attr,
1376 or the attr not being a list, are suppressed.
1377*/
1378
1379static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001380merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001381{
1382 PyObject *list;
1383 int result = 0;
1384
1385 assert(PyDict_Check(dict));
1386 assert(obj);
1387 assert(attrname);
1388
1389 list = PyObject_GetAttrString(obj, attrname);
1390 if (list == NULL)
1391 PyErr_Clear();
1392
1393 else if (PyList_Check(list)) {
1394 int i;
1395 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1396 PyObject *item = PyList_GET_ITEM(list, i);
1397 if (PyString_Check(item)) {
1398 result = PyDict_SetItem(dict, item, Py_None);
1399 if (result < 0)
1400 break;
1401 }
1402 }
1403 }
1404
1405 Py_XDECREF(list);
1406 return result;
1407}
1408
Tim Peters7eea37e2001-09-04 22:08:56 +00001409/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1410 docstring, which should be kept in synch with this implementation. */
1411
1412PyObject *
1413PyObject_Dir(PyObject *arg)
1414{
1415 /* Set exactly one of these non-NULL before the end. */
1416 PyObject *result = NULL; /* result list */
1417 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1418
1419 /* If NULL arg, return the locals. */
1420 if (arg == NULL) {
1421 PyObject *locals = PyEval_GetLocals();
1422 if (locals == NULL)
1423 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001424 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001425 if (result == NULL)
1426 goto error;
1427 }
1428
1429 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001430 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001431 masterdict = PyObject_GetAttrString(arg, "__dict__");
1432 if (masterdict == NULL)
1433 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001434 if (!PyDict_Check(masterdict)) {
1435 PyErr_SetString(PyExc_TypeError,
1436 "module.__dict__ is not a dictionary");
1437 goto error;
1438 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001439 }
1440
1441 /* Elif some form of type or class, grab its dict and its bases.
1442 We deliberately don't suck up its __class__, as methods belonging
1443 to the metaclass would probably be more confusing than helpful. */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001444 else if (PyType_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001445 masterdict = PyDict_New();
1446 if (masterdict == NULL)
1447 goto error;
1448 if (merge_class_dict(masterdict, arg) < 0)
1449 goto error;
1450 }
1451
1452 /* Else look at its dict, and the attrs reachable from its class. */
1453 else {
1454 PyObject *itsclass;
1455 /* Create a dict to start with. CAUTION: Not everything
1456 responding to __dict__ returns a dict! */
1457 masterdict = PyObject_GetAttrString(arg, "__dict__");
1458 if (masterdict == NULL) {
1459 PyErr_Clear();
1460 masterdict = PyDict_New();
1461 }
1462 else if (!PyDict_Check(masterdict)) {
1463 Py_DECREF(masterdict);
1464 masterdict = PyDict_New();
1465 }
1466 else {
1467 /* The object may have returned a reference to its
1468 dict, so copy it to avoid mutating it. */
1469 PyObject *temp = PyDict_Copy(masterdict);
1470 Py_DECREF(masterdict);
1471 masterdict = temp;
1472 }
1473 if (masterdict == NULL)
1474 goto error;
1475
Tim Peters305b5852001-09-17 02:38:46 +00001476 /* Merge in __members__ and __methods__ (if any).
1477 XXX Would like this to go away someday; for now, it's
1478 XXX needed to get at im_self etc of method objects. */
1479 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1480 goto error;
1481 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1482 goto error;
1483
Tim Peters7eea37e2001-09-04 22:08:56 +00001484 /* Merge in attrs reachable from its class.
1485 CAUTION: Not all objects have a __class__ attr. */
1486 itsclass = PyObject_GetAttrString(arg, "__class__");
1487 if (itsclass == NULL)
1488 PyErr_Clear();
1489 else {
1490 int status = merge_class_dict(masterdict, itsclass);
1491 Py_DECREF(itsclass);
1492 if (status < 0)
1493 goto error;
1494 }
1495 }
1496
1497 assert((result == NULL) ^ (masterdict == NULL));
1498 if (masterdict != NULL) {
1499 /* The result comes from its keys. */
1500 assert(result == NULL);
1501 result = PyDict_Keys(masterdict);
1502 if (result == NULL)
1503 goto error;
1504 }
1505
1506 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001507 if (!PyList_Check(result)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001508 PyErr_Format(PyExc_TypeError,
1509 "Expected keys() to be a list, not '%.200s'",
1510 result->ob_type->tp_name);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001511 goto error;
1512 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001513 if (PyList_Sort(result) != 0)
1514 goto error;
1515 else
1516 goto normal_return;
1517
1518 error:
1519 Py_XDECREF(result);
1520 result = NULL;
1521 /* fall through */
1522 normal_return:
1523 Py_XDECREF(masterdict);
1524 return result;
1525}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001526
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001527/*
1528NoObject is usable as a non-NULL undefined value, used by the macro None.
1529There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001530so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001531(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001532*/
1533
Guido van Rossum0c182a11992-03-27 17:26:13 +00001534/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001535static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001536none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001537{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001538 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001539}
1540
Barry Warsaw9bf16442001-01-23 16:24:35 +00001541/* ARGUSED */
1542static void
Tim Peters803526b2002-07-07 05:13:56 +00001543none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001544{
1545 /* This should never get called, but we also don't want to SEGV if
1546 * we accidently decref None out of existance.
1547 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001548 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001549}
1550
1551
Guido van Rossumba21a492001-08-16 08:17:26 +00001552static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001553 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001554 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001555 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001556 0,
1557 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001558 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001559 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001560 0, /*tp_getattr*/
1561 0, /*tp_setattr*/
1562 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001563 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001564 0, /*tp_as_number*/
1565 0, /*tp_as_sequence*/
1566 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001567 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001568};
1569
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001570PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001571 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001572};
1573
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001574/* NotImplemented is an object that can be used to signal that an
1575 operation is not implemented for the given type combination. */
1576
1577static PyObject *
1578NotImplemented_repr(PyObject *op)
1579{
1580 return PyString_FromString("NotImplemented");
1581}
1582
1583static PyTypeObject PyNotImplemented_Type = {
1584 PyObject_HEAD_INIT(&PyType_Type)
1585 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001586 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001587 0,
1588 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001589 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001590 0, /*tp_print*/
1591 0, /*tp_getattr*/
1592 0, /*tp_setattr*/
1593 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001594 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001595 0, /*tp_as_number*/
1596 0, /*tp_as_sequence*/
1597 0, /*tp_as_mapping*/
1598 0, /*tp_hash */
1599};
1600
1601PyObject _Py_NotImplementedStruct = {
1602 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1603};
1604
Guido van Rossumba21a492001-08-16 08:17:26 +00001605void
1606_Py_ReadyTypes(void)
1607{
1608 if (PyType_Ready(&PyType_Type) < 0)
1609 Py_FatalError("Can't initialize 'type'");
1610
Fred Drake0a4dd392004-07-02 18:57:45 +00001611 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1612 Py_FatalError("Can't initialize 'weakref'");
1613
Guido van Rossum77f6a652002-04-03 22:41:51 +00001614 if (PyType_Ready(&PyBool_Type) < 0)
1615 Py_FatalError("Can't initialize 'bool'");
1616
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001617 if (PyType_Ready(&PyBytes_Type) < 0)
1618 Py_FatalError("Can't initialize 'bytes'");
1619
Guido van Rossumcacfc072002-05-24 19:01:59 +00001620 if (PyType_Ready(&PyString_Type) < 0)
1621 Py_FatalError("Can't initialize 'str'");
1622
Guido van Rossumba21a492001-08-16 08:17:26 +00001623 if (PyType_Ready(&PyList_Type) < 0)
1624 Py_FatalError("Can't initialize 'list'");
1625
1626 if (PyType_Ready(&PyNone_Type) < 0)
1627 Py_FatalError("Can't initialize type(None)");
1628
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001629 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1630 Py_FatalError("Can't initialize type(Ellipsis)");
1631
Guido van Rossumba21a492001-08-16 08:17:26 +00001632 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1633 Py_FatalError("Can't initialize type(NotImplemented)");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001634
1635 if (PyType_Ready(&PyCode_Type) < 0)
1636 Py_FatalError("Can't initialize 'code'");
Guido van Rossumba21a492001-08-16 08:17:26 +00001637}
1638
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001639
Guido van Rossum84a90321996-05-22 16:34:47 +00001640#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001641
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001642void
Fred Drake100814d2000-07-09 15:48:49 +00001643_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001644{
Tim Peters34592512002-07-11 06:23:50 +00001645 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001646 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001647 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001648 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001649}
1650
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001651void
Fred Drake100814d2000-07-09 15:48:49 +00001652_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001653{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001654#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001655 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001656#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001657 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001658 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001659 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001660 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001661 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001662#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001663 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1664 if (p == op)
1665 break;
1666 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001667 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001668 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001669#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001670 op->_ob_next->_ob_prev = op->_ob_prev;
1671 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001672 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001673 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001674}
1675
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001676void
Fred Drake100814d2000-07-09 15:48:49 +00001677_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001678{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001679 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001680 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001681 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001682}
1683
Tim Peters269b2a62003-04-17 19:52:29 +00001684/* Print all live objects. Because PyObject_Print is called, the
1685 * interpreter must be in a healthy state.
1686 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001687void
Fred Drake100814d2000-07-09 15:48:49 +00001688_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001689{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001690 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001691 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001692 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001693 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001694 if (PyObject_Print(op, fp, 0) != 0)
1695 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001696 putc('\n', fp);
1697 }
1698}
1699
Tim Peters269b2a62003-04-17 19:52:29 +00001700/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1701 * doesn't make any calls to the Python C API, so is always safe to call.
1702 */
1703void
1704_Py_PrintReferenceAddresses(FILE *fp)
1705{
1706 PyObject *op;
1707 fprintf(fp, "Remaining object addresses:\n");
1708 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001709 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1710 op->ob_refcnt, op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001711}
1712
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001713PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001714_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001715{
1716 int i, n;
1717 PyObject *t = NULL;
1718 PyObject *res, *op;
1719
1720 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1721 return NULL;
1722 op = refchain._ob_next;
1723 res = PyList_New(0);
1724 if (res == NULL)
1725 return NULL;
1726 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1727 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001728 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001729 op = op->_ob_next;
1730 if (op == &refchain)
1731 return res;
1732 }
1733 if (PyList_Append(res, op) < 0) {
1734 Py_DECREF(res);
1735 return NULL;
1736 }
1737 op = op->_ob_next;
1738 }
1739 return res;
1740}
1741
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001742#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001743
1744
1745/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001746PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001747
1748
1749/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001750Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001751
1752
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001753/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001754
Thomas Wouters334fb892000-07-25 12:56:38 +00001755void *
Fred Drake100814d2000-07-09 15:48:49 +00001756PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001757{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001758 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001759}
1760
Thomas Wouters334fb892000-07-25 12:56:38 +00001761void *
1762PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001763{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001764 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001765}
1766
1767void
Thomas Wouters334fb892000-07-25 12:56:38 +00001768PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001769{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001770 PyMem_FREE(p);
1771}
1772
1773
Guido van Rossum86610361998-04-10 22:32:46 +00001774/* These methods are used to control infinite recursion in repr, str, print,
1775 etc. Container objects that may recursively contain themselves,
1776 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1777 Py_ReprLeave() to avoid infinite recursion.
1778
1779 Py_ReprEnter() returns 0 the first time it is called for a particular
1780 object and 1 every time thereafter. It returns -1 if an exception
1781 occurred. Py_ReprLeave() has no return value.
1782
1783 See dictobject.c and listobject.c for examples of use.
1784*/
1785
1786#define KEY "Py_Repr"
1787
1788int
Fred Drake100814d2000-07-09 15:48:49 +00001789Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001790{
1791 PyObject *dict;
1792 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001793 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001794
1795 dict = PyThreadState_GetDict();
1796 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001797 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001798 list = PyDict_GetItemString(dict, KEY);
1799 if (list == NULL) {
1800 list = PyList_New(0);
1801 if (list == NULL)
1802 return -1;
1803 if (PyDict_SetItemString(dict, KEY, list) < 0)
1804 return -1;
1805 Py_DECREF(list);
1806 }
1807 i = PyList_GET_SIZE(list);
1808 while (--i >= 0) {
1809 if (PyList_GET_ITEM(list, i) == obj)
1810 return 1;
1811 }
1812 PyList_Append(list, obj);
1813 return 0;
1814}
1815
1816void
Fred Drake100814d2000-07-09 15:48:49 +00001817Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001818{
1819 PyObject *dict;
1820 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001822
1823 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00001824 if (dict == NULL)
1825 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001826 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00001827 if (list == NULL || !PyList_Check(list))
1828 return;
Guido van Rossum86610361998-04-10 22:32:46 +00001829 i = PyList_GET_SIZE(list);
1830 /* Count backwards because we always expect obj to be list[-1] */
1831 while (--i >= 0) {
1832 if (PyList_GET_ITEM(list, i) == obj) {
1833 PyList_SetSlice(list, i, i + 1, NULL);
1834 break;
1835 }
1836 }
1837}
Guido van Rossumd724b232000-03-13 16:01:29 +00001838
Tim Peters803526b2002-07-07 05:13:56 +00001839/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001840
Tim Peters803526b2002-07-07 05:13:56 +00001841/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001842int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001843
Tim Peters803526b2002-07-07 05:13:56 +00001844/* List of objects that still need to be cleaned up, singly linked via their
1845 * gc headers' gc_prev pointers.
1846 */
1847PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001848
Tim Peters803526b2002-07-07 05:13:56 +00001849/* Add op to the _PyTrash_delete_later list. Called when the current
1850 * call-stack depth gets large. op must be a currently untracked gc'ed
1851 * object, with refcount 0. Py_DECREF must already have been called on it.
1852 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001853void
Fred Drake100814d2000-07-09 15:48:49 +00001854_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001855{
Tim Peters803526b2002-07-07 05:13:56 +00001856 assert(PyObject_IS_GC(op));
1857 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1858 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00001859 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00001860 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001861}
1862
Tim Peters803526b2002-07-07 05:13:56 +00001863/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1864 * the call-stack unwinds again.
1865 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001866void
Fred Drake100814d2000-07-09 15:48:49 +00001867_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001868{
1869 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00001870 PyObject *op = _PyTrash_delete_later;
1871 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001872
Neil Schemenauerf589c052002-03-29 03:05:54 +00001873 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00001874 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001875
Tim Peters803526b2002-07-07 05:13:56 +00001876 /* Call the deallocator directly. This used to try to
1877 * fool Py_DECREF into calling it indirectly, but
1878 * Py_DECREF was already called on this object, and in
1879 * assorted non-release builds calling Py_DECREF again ends
1880 * up distorting allocation statistics.
1881 */
1882 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00001883 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00001884 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00001885 --_PyTrash_delete_nesting;
1886 }
1887}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001888
1889#ifdef __cplusplus
1890}
1891#endif
1892