blob: 981654159d04fb79a749fa102aa7834d62a22fb8 [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"
Benjamin Petersonc4853612009-04-20 02:09:13 +00005#include "frameobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Anthony Baxterac6bd462006-04-13 02:06:09 +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;
Armin Rigoe1709372006-04-12 17:06:05 +000013
14Py_ssize_t
15_Py_GetRefTotal(void)
16{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000017 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;
Armin Rigoe1709372006-04-12 17:06:05 +000029}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Mark Hammonda2905272002-07-29 13:42:14 +000032int Py_DivisionWarningFlag;
Neal Norwitz8b2bfbc2007-05-23 06:35:32 +000033int Py_Py3kWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000034
Guido van Rossum3f5da241990-12-20 15:06:42 +000035/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
36 These are used by the individual routines for object creation.
37 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038
Tim Peters78be7992003-03-23 02:51:01 +000039#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000040/* Head of circular doubly-linked list of all objects. These are linked
41 * together via the _ob_prev and _ob_next members of a PyObject, which
42 * exist only in a Py_TRACE_REFS build.
43 */
Tim Peters78be7992003-03-23 02:51:01 +000044static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000045
Tim Peters7571a0f2003-03-23 17:52:28 +000046/* Insert op at the front of the list of all objects. If force is true,
47 * op is added even if _ob_prev and _ob_next are non-NULL already. If
48 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
49 * force should be true if and only if op points to freshly allocated,
50 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000051 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000052 * Note that objects are normally added to the list via _Py_NewReference,
53 * which is called by PyObject_Init. Not all objects are initialized that
54 * way, though; exceptions include statically allocated type objects, and
55 * statically allocated singletons (like Py_True and Py_None).
56 */
Tim Peters36eb4df2003-03-23 03:33:13 +000057void
Tim Peters7571a0f2003-03-23 17:52:28 +000058_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000059{
Tim Peters7571a0f2003-03-23 17:52:28 +000060#ifdef Py_DEBUG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000061 if (!force) {
62 /* If it's initialized memory, op must be in or out of
63 * the list unambiguously.
64 */
65 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
66 }
Tim Peters78be7992003-03-23 02:51:01 +000067#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000068 if (force || op->_ob_prev == NULL) {
69 op->_ob_next = refchain._ob_next;
70 op->_ob_prev = &refchain;
71 refchain._ob_next->_ob_prev = op;
72 refchain._ob_next = op;
73 }
Tim Peters7571a0f2003-03-23 17:52:28 +000074}
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000075#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000076
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000077#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000078static PyTypeObject *type_list;
Andrew M. Kuchling2060d1b2006-04-18 11:49:53 +000079/* All types are added to type_list, at least when
Martin v. Löwis45294a92006-04-18 06:24:08 +000080 they get one object created. That makes them
81 immortal, which unfortunately contributes to
82 garbage itself. If unlist_types_without_objects
83 is set, they will be removed from the type_list
84 once the last object is deallocated. */
85int unlist_types_without_objects;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000086extern int tuple_zero_allocs, fast_tuple_allocs;
87extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000088extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000089void
Martin v. Löwis45294a92006-04-18 06:24:08 +000090dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000091{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000092 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000093
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000094 for (tp = type_list; tp; tp = tp->tp_next)
95 fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",
96 tp->tp_name, tp->tp_allocs, tp->tp_frees,
97 tp->tp_maxalloc);
98 fprintf(f, "fast tuple allocs: %d, empty: %d\n",
99 fast_tuple_allocs, tuple_zero_allocs);
100 fprintf(f, "fast int allocs: pos: %d, neg: %d\n",
101 quick_int_allocs, quick_neg_int_allocs);
102 fprintf(f, "null strings: %d, 1-strings: %d\n",
103 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000104}
105
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000106PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000107get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000108{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000109 PyTypeObject *tp;
110 PyObject *result;
111 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000112
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000113 result = PyList_New(0);
114 if (result == NULL)
115 return NULL;
116 for (tp = type_list; tp; tp = tp->tp_next) {
117 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
118 tp->tp_frees, tp->tp_maxalloc);
119 if (v == NULL) {
120 Py_DECREF(result);
121 return NULL;
122 }
123 if (PyList_Append(result, v) < 0) {
124 Py_DECREF(v);
125 Py_DECREF(result);
126 return NULL;
127 }
128 Py_DECREF(v);
129 }
130 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000131}
132
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000133void
Fred Drake100814d2000-07-09 15:48:49 +0000134inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000135{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000136 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
137 /* first time; insert in linked list */
138 if (tp->tp_next != NULL) /* sanity check */
139 Py_FatalError("XXX inc_count sanity check");
140 if (type_list)
141 type_list->tp_prev = tp;
142 tp->tp_next = type_list;
143 /* Note that as of Python 2.2, heap-allocated type objects
144 * can go away, but this code requires that they stay alive
145 * until program exit. That's why we're careful with
146 * refcounts here. type_list gets a new reference to tp,
147 * while ownership of the reference type_list used to hold
148 * (if any) was transferred to tp->tp_next in the line above.
149 * tp is thus effectively immortal after this.
150 */
151 Py_INCREF(tp);
152 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000153#ifdef Py_TRACE_REFS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000154 /* Also insert in the doubly-linked list of all objects,
155 * if not already there.
156 */
157 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000158#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000159 }
160 tp->tp_allocs++;
161 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
162 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000163}
Martin v. Löwis45294a92006-04-18 06:24:08 +0000164
165void dec_count(PyTypeObject *tp)
166{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000167 tp->tp_frees++;
168 if (unlist_types_without_objects &&
169 tp->tp_allocs == tp->tp_frees) {
170 /* unlink the type from type_list */
171 if (tp->tp_prev)
172 tp->tp_prev->tp_next = tp->tp_next;
173 else
174 type_list = tp->tp_next;
175 if (tp->tp_next)
176 tp->tp_next->tp_prev = tp->tp_prev;
177 tp->tp_next = tp->tp_prev = NULL;
178 Py_DECREF(tp);
179 }
Martin v. Löwis45294a92006-04-18 06:24:08 +0000180}
181
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000182#endif
183
Tim Peters7c321a82002-07-09 02:57:01 +0000184#ifdef Py_REF_DEBUG
185/* Log a fatal error; doesn't return. */
186void
187_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
188{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000189 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000190
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000191 PyOS_snprintf(buf, sizeof(buf),
192 "%s:%i object at %p has negative ref count "
193 "%" PY_FORMAT_SIZE_T "d",
194 fname, lineno, op, op->ob_refcnt);
195 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000196}
197
198#endif /* Py_REF_DEBUG */
199
Thomas Heller1328b522004-04-22 17:23:49 +0000200void
201Py_IncRef(PyObject *o)
202{
203 Py_XINCREF(o);
204}
205
206void
207Py_DecRef(PyObject *o)
208{
209 Py_XDECREF(o);
210}
211
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000213PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000215 if (op == NULL)
216 return PyErr_NoMemory();
217 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
218 Py_TYPE(op) = tp;
219 _Py_NewReference(op);
220 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221}
222
Guido van Rossumb18618d2000-05-03 23:44:39 +0000223PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000224PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000225{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000226 if (op == NULL)
227 return (PyVarObject *) PyErr_NoMemory();
228 /* Any changes should be reflected in PyObject_INIT_VAR */
229 op->ob_size = size;
230 Py_TYPE(op) = tp;
231 _Py_NewReference((PyObject *)op);
232 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000233}
234
235PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000236_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000237{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000238 PyObject *op;
239 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
240 if (op == NULL)
241 return PyErr_NoMemory();
242 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000243}
244
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000245PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000246_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000248 PyVarObject *op;
249 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
250 op = (PyVarObject *) PyObject_MALLOC(size);
251 if (op == NULL)
252 return (PyVarObject *)PyErr_NoMemory();
253 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000254}
255
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000256/* for binary compatibility with 2.2 */
257#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000258void
Fred Drake100814d2000-07-09 15:48:49 +0000259_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000260{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000261 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262}
263
Neal Norwitz1a997502003-01-13 20:13:12 +0000264/* Implementation of PyObject_Print with recursion checking */
265static int
266internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000268 int ret = 0;
269 if (nesting > 10) {
270 PyErr_SetString(PyExc_RuntimeError, "print recursion");
271 return -1;
272 }
273 if (PyErr_CheckSignals())
274 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000275#ifdef USE_STACKCHECK
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000276 if (PyOS_CheckStack()) {
277 PyErr_SetString(PyExc_MemoryError, "stack overflow");
278 return -1;
279 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000280#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000281 clearerr(fp); /* Clear any previous error condition */
282 if (op == NULL) {
283 Py_BEGIN_ALLOW_THREADS
284 fprintf(fp, "<nil>");
285 Py_END_ALLOW_THREADS
286 }
287 else {
288 if (op->ob_refcnt <= 0)
289 /* XXX(twouters) cast refcount to long until %zd is
290 universally available */
291 Py_BEGIN_ALLOW_THREADS
292 fprintf(fp, "<refcnt %ld at %p>",
293 (long)op->ob_refcnt, op);
294 Py_END_ALLOW_THREADS
295 else if (Py_TYPE(op)->tp_print == NULL) {
296 PyObject *s;
297 if (flags & Py_PRINT_RAW)
298 s = PyObject_Str(op);
299 else
300 s = PyObject_Repr(op);
301 if (s == NULL)
302 ret = -1;
303 else {
304 ret = internal_print(s, fp, Py_PRINT_RAW,
305 nesting+1);
306 }
307 Py_XDECREF(s);
308 }
309 else
310 ret = (*Py_TYPE(op)->tp_print)(op, fp, flags);
311 }
312 if (ret == 0) {
313 if (ferror(fp)) {
314 PyErr_SetFromErrno(PyExc_IOError);
315 clearerr(fp);
316 ret = -1;
317 }
318 }
319 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320}
321
Neal Norwitz1a997502003-01-13 20:13:12 +0000322int
323PyObject_Print(PyObject *op, FILE *fp, int flags)
324{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000325 return internal_print(op, fp, flags, 0);
Neal Norwitz1a997502003-01-13 20:13:12 +0000326}
327
328
Barry Warsaw9bf16442001-01-23 16:24:35 +0000329/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000330void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000331{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000332 if (op == NULL)
333 fprintf(stderr, "NULL\n");
334 else {
Georg Brandle9b91212009-04-05 21:26:31 +0000335#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000336 PyGILState_STATE gil;
Georg Brandle9b91212009-04-05 21:26:31 +0000337#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000338 fprintf(stderr, "object : ");
Georg Brandle9b91212009-04-05 21:26:31 +0000339#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000340 gil = PyGILState_Ensure();
Georg Brandle9b91212009-04-05 21:26:31 +0000341#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000342 (void)PyObject_Print(op, stderr, 0);
Georg Brandle9b91212009-04-05 21:26:31 +0000343#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000344 PyGILState_Release(gil);
Georg Brandle9b91212009-04-05 21:26:31 +0000345#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000346 /* XXX(twouters) cast refcount to long until %zd is
347 universally available */
348 fprintf(stderr, "\n"
349 "type : %s\n"
350 "refcount: %ld\n"
351 "address : %p\n",
352 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
353 (long)op->ob_refcnt,
354 op);
355 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000356}
Barry Warsaw903138f2001-01-23 16:33:18 +0000357
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000359PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000361 if (PyErr_CheckSignals())
362 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000363#ifdef USE_STACKCHECK
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000364 if (PyOS_CheckStack()) {
365 PyErr_SetString(PyExc_MemoryError, "stack overflow");
366 return NULL;
367 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000368#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000369 if (v == NULL)
370 return PyString_FromString("<NULL>");
371 else if (Py_TYPE(v)->tp_repr == NULL)
372 return PyString_FromFormat("<%s object at %p>",
373 Py_TYPE(v)->tp_name, v);
374 else {
375 PyObject *res;
376 res = (*Py_TYPE(v)->tp_repr)(v);
377 if (res == NULL)
378 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000379#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000380 if (PyUnicode_Check(res)) {
381 PyObject* str;
382 str = PyUnicode_AsEncodedString(res, NULL, NULL);
383 Py_DECREF(res);
384 if (str)
385 res = str;
386 else
387 return NULL;
388 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000389#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000390 if (!PyString_Check(res)) {
391 PyErr_Format(PyExc_TypeError,
392 "__repr__ returned non-string (type %.200s)",
393 Py_TYPE(res)->tp_name);
394 Py_DECREF(res);
395 return NULL;
396 }
397 return res;
398 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399}
400
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000401PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000402_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000403{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000404 PyObject *res;
405 int type_ok;
406 if (v == NULL)
407 return PyString_FromString("<NULL>");
408 if (PyString_CheckExact(v)) {
409 Py_INCREF(v);
410 return v;
411 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000412#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000413 if (PyUnicode_CheckExact(v)) {
414 Py_INCREF(v);
415 return v;
416 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000417#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000418 if (Py_TYPE(v)->tp_str == NULL)
419 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000420
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000421 /* It is possible for a type to have a tp_str representation that loops
422 infinitely. */
423 if (Py_EnterRecursiveCall(" while getting the str of an object"))
424 return NULL;
425 res = (*Py_TYPE(v)->tp_str)(v);
426 Py_LeaveRecursiveCall();
427 if (res == NULL)
428 return NULL;
429 type_ok = PyString_Check(res);
Neil Schemenauercf52c072005-08-12 17:34:58 +0000430#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000431 type_ok = type_ok || PyUnicode_Check(res);
Neil Schemenauercf52c072005-08-12 17:34:58 +0000432#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000433 if (!type_ok) {
434 PyErr_Format(PyExc_TypeError,
435 "__str__ returned non-string (type %.200s)",
436 Py_TYPE(res)->tp_name);
437 Py_DECREF(res);
438 return NULL;
439 }
440 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000441}
442
443PyObject *
444PyObject_Str(PyObject *v)
445{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000446 PyObject *res = _PyObject_Str(v);
447 if (res == NULL)
448 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000449#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000450 if (PyUnicode_Check(res)) {
451 PyObject* str;
452 str = PyUnicode_AsEncodedString(res, NULL, NULL);
453 Py_DECREF(res);
454 if (str)
455 res = str;
456 else
457 return NULL;
458 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000459#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000460 assert(PyString_Check(res));
461 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000462}
463
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000464#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000465PyObject *
466PyObject_Unicode(PyObject *v)
467{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000468 PyObject *res;
469 PyObject *func;
470 PyObject *str;
471 int unicode_method_found = 0;
472 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000473
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000474 if (v == NULL) {
475 res = PyString_FromString("<NULL>");
476 if (res == NULL)
477 return NULL;
478 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
479 Py_DECREF(res);
480 return str;
481 } else if (PyUnicode_CheckExact(v)) {
482 Py_INCREF(v);
483 return v;
484 }
Nick Coghlan524b7772008-07-08 14:08:04 +0000485
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000486 /* Try the __unicode__ method */
487 if (unicodestr == NULL) {
488 unicodestr= PyString_InternFromString("__unicode__");
489 if (unicodestr == NULL)
490 return NULL;
491 }
492 if (PyInstance_Check(v)) {
493 /* We're an instance of a classic class */
494 /* Try __unicode__ from the instance -- alas we have no type */
495 func = PyObject_GetAttr(v, unicodestr);
496 if (func != NULL) {
497 unicode_method_found = 1;
498 res = PyObject_CallFunctionObjArgs(func, NULL);
499 Py_DECREF(func);
500 }
501 else {
502 PyErr_Clear();
503 }
504 }
505 else {
506 /* Not a classic class instance, try __unicode__ from type */
507 /* _PyType_Lookup doesn't create a reference */
508 func = _PyType_Lookup(Py_TYPE(v), unicodestr);
509 if (func != NULL) {
510 unicode_method_found = 1;
511 res = PyObject_CallFunctionObjArgs(func, v, NULL);
512 }
513 else {
514 PyErr_Clear();
515 }
516 }
Nick Coghlan524b7772008-07-08 14:08:04 +0000517
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000518 /* Didn't find __unicode__ */
519 if (!unicode_method_found) {
520 if (PyUnicode_Check(v)) {
521 /* For a Unicode subtype that's didn't overwrite __unicode__,
522 return a true Unicode object with the same data. */
523 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
524 PyUnicode_GET_SIZE(v));
525 }
526 if (PyString_CheckExact(v)) {
527 Py_INCREF(v);
528 res = v;
529 }
530 else {
531 if (Py_TYPE(v)->tp_str != NULL)
532 res = (*Py_TYPE(v)->tp_str)(v);
533 else
534 res = PyObject_Repr(v);
535 }
536 }
Nick Coghlan524b7772008-07-08 14:08:04 +0000537
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000538 if (res == NULL)
539 return NULL;
540 if (!PyUnicode_Check(res)) {
541 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
542 Py_DECREF(res);
543 res = str;
544 }
545 return res;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000546}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000547#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000548
549
Guido van Rossuma4073002002-05-31 20:03:54 +0000550/* Helper to warn about deprecated tp_compare return values. Return:
551 -2 for an exception;
552 -1 if v < w;
553 0 if v == w;
554 1 if v > w.
555 (This function cannot return 2.)
556*/
557static int
558adjust_tp_compare(int c)
559{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000560 if (PyErr_Occurred()) {
561 if (c != -1 && c != -2) {
562 PyObject *t, *v, *tb;
563 PyErr_Fetch(&t, &v, &tb);
564 if (PyErr_Warn(PyExc_RuntimeWarning,
565 "tp_compare didn't return -1 or -2 "
566 "for exception") < 0) {
567 Py_XDECREF(t);
568 Py_XDECREF(v);
569 Py_XDECREF(tb);
570 }
571 else
572 PyErr_Restore(t, v, tb);
573 }
574 return -2;
575 }
576 else if (c < -1 || c > 1) {
577 if (PyErr_Warn(PyExc_RuntimeWarning,
578 "tp_compare didn't return -1, 0 or 1") < 0)
579 return -2;
580 else
581 return c < -1 ? -1 : 1;
582 }
583 else {
584 assert(c >= -1 && c <= 1);
585 return c;
586 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000587}
588
589
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000590/* Macro to get the tp_richcompare field of a type if defined */
591#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000592 ? (t)->tp_richcompare : NULL)
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000593
Guido van Rossume797ec12001-01-17 15:24:28 +0000594/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000595int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000596
Guido van Rossume797ec12001-01-17 15:24:28 +0000597/* Try a genuine rich comparison, returning an object. Return:
598 NULL for exception;
599 NotImplemented if this particular rich comparison is not implemented or
600 undefined;
601 some object not equal to NotImplemented if it is implemented
602 (this latter object may not be a Boolean).
603*/
604static PyObject *
605try_rich_compare(PyObject *v, PyObject *w, int op)
606{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000607 richcmpfunc f;
608 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000609
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000610 if (v->ob_type != w->ob_type &&
611 PyType_IsSubtype(w->ob_type, v->ob_type) &&
612 (f = RICHCOMPARE(w->ob_type)) != NULL) {
613 res = (*f)(w, v, _Py_SwappedOp[op]);
614 if (res != Py_NotImplemented)
615 return res;
616 Py_DECREF(res);
617 }
618 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
619 res = (*f)(v, w, op);
620 if (res != Py_NotImplemented)
621 return res;
622 Py_DECREF(res);
623 }
624 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
625 return (*f)(w, v, _Py_SwappedOp[op]);
626 }
627 res = Py_NotImplemented;
628 Py_INCREF(res);
629 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000630}
631
632/* Try a genuine rich comparison, returning an int. Return:
633 -1 for exception (including the case where try_rich_compare() returns an
634 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000635 0 if the outcome is false;
636 1 if the outcome is true;
637 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000638*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000639static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000640try_rich_compare_bool(PyObject *v, PyObject *w, int op)
641{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000642 PyObject *res;
643 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000644
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000645 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
646 return 2; /* Shortcut, avoid INCREF+DECREF */
647 res = try_rich_compare(v, w, op);
648 if (res == NULL)
649 return -1;
650 if (res == Py_NotImplemented) {
651 Py_DECREF(res);
652 return 2;
653 }
654 ok = PyObject_IsTrue(res);
655 Py_DECREF(res);
656 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000657}
658
659/* Try rich comparisons to determine a 3-way comparison. Return:
660 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000661 -1 if v < w;
662 0 if v == w;
663 1 if v > w;
664 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000665*/
666static int
667try_rich_to_3way_compare(PyObject *v, PyObject *w)
668{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000669 static struct { int op; int outcome; } tries[3] = {
670 /* Try this operator, and if it is true, use this outcome: */
671 {Py_EQ, 0},
672 {Py_LT, -1},
673 {Py_GT, 1},
674 };
675 int i;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000676
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000677 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
678 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000679
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000680 for (i = 0; i < 3; i++) {
681 switch (try_rich_compare_bool(v, w, tries[i].op)) {
682 case -1:
683 return -2;
684 case 1:
685 return tries[i].outcome;
686 }
687 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000688
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000689 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000690}
691
692/* Try a 3-way comparison, returning an int. Return:
693 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000694 -1 if v < w;
695 0 if v == w;
696 1 if v > w;
697 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000698*/
699static int
700try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000701{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000702 int c;
703 cmpfunc f;
Guido van Rossume797ec12001-01-17 15:24:28 +0000704
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000705 /* Comparisons involving instances are given to instance_compare,
706 which has the same return conventions as this function. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000707
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000708 f = v->ob_type->tp_compare;
709 if (PyInstance_Check(v))
710 return (*f)(v, w);
711 if (PyInstance_Check(w))
712 return (*w->ob_type->tp_compare)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000713
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000714 /* If both have the same (non-NULL) tp_compare, use it. */
715 if (f != NULL && f == w->ob_type->tp_compare) {
716 c = (*f)(v, w);
717 return adjust_tp_compare(c);
718 }
Guido van Rossumab3b0342001-09-18 20:38:53 +0000719
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000720 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
721 if (f == _PyObject_SlotCompare ||
722 w->ob_type->tp_compare == _PyObject_SlotCompare)
723 return _PyObject_SlotCompare(v, w);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000724
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000725 /* If we're here, v and w,
726 a) are not instances;
727 b) have different types or a type without tp_compare; and
728 c) don't have a user-defined tp_compare.
729 tp_compare implementations in C assume that both arguments
730 have their type, so we give up if the coercion fails or if
731 it yields types which are still incompatible (which can
732 happen with a user-defined nb_coerce).
733 */
734 c = PyNumber_CoerceEx(&v, &w);
735 if (c < 0)
736 return -2;
737 if (c > 0)
738 return 2;
739 f = v->ob_type->tp_compare;
740 if (f != NULL && f == w->ob_type->tp_compare) {
741 c = (*f)(v, w);
742 Py_DECREF(v);
743 Py_DECREF(w);
744 return adjust_tp_compare(c);
745 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000746
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000747 /* No comparison defined */
748 Py_DECREF(v);
749 Py_DECREF(w);
750 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000751}
752
Guido van Rossume797ec12001-01-17 15:24:28 +0000753/* Final fallback 3-way comparison, returning an int. Return:
754 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000755 -1 if v < w;
756 0 if v == w;
757 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000758*/
759static int
760default_3way_compare(PyObject *v, PyObject *w)
761{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000762 int c;
763 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000764
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000765 if (v->ob_type == w->ob_type) {
766 /* When comparing these pointers, they must be cast to
767 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
768 * uintptr_t). ANSI specifies that pointer compares other
769 * than == and != to non-related structures are undefined.
770 */
771 Py_uintptr_t vv = (Py_uintptr_t)v;
772 Py_uintptr_t ww = (Py_uintptr_t)w;
773 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
774 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000775
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000776 /* None is smaller than anything */
777 if (v == Py_None)
778 return -1;
779 if (w == Py_None)
780 return 1;
Guido van Rossum0871e932001-01-22 19:28:09 +0000781
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000782 /* different type: compare type names; numbers are smaller */
783 if (PyNumber_Check(v))
784 vname = "";
785 else
786 vname = v->ob_type->tp_name;
787 if (PyNumber_Check(w))
788 wname = "";
789 else
790 wname = w->ob_type->tp_name;
791 c = strcmp(vname, wname);
792 if (c < 0)
793 return -1;
794 if (c > 0)
795 return 1;
796 /* Same type name, or (more likely) incomparable numeric types */
797 return ((Py_uintptr_t)(v->ob_type) < (
798 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000799}
800
Tim Peters6d60b2e2001-05-07 20:53:51 +0000801/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000802 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000803 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000804 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000805 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000806 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000807 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000808*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000809static int
Fred Drake100814d2000-07-09 15:48:49 +0000810do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000811{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000812 int c;
813 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000814
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000815 if (v->ob_type == w->ob_type
816 && (f = v->ob_type->tp_compare) != NULL) {
817 c = (*f)(v, w);
818 if (PyInstance_Check(v)) {
819 /* Instance tp_compare has a different signature.
820 But if it returns undefined we fall through. */
821 if (c != 2)
822 return c;
823 /* Else fall through to try_rich_to_3way_compare() */
824 }
825 else
826 return adjust_tp_compare(c);
827 }
828 /* We only get here if one of the following is true:
829 a) v and w have different types
830 b) v and w have the same type, which doesn't have tp_compare
831 c) v and w are instances, and either __cmp__ is not defined or
832 __cmp__ returns NotImplemented
833 */
834 c = try_rich_to_3way_compare(v, w);
835 if (c < 2)
836 return c;
837 c = try_3way_compare(v, w);
838 if (c < 2)
839 return c;
840 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000841}
842
Tim Petersc99213f2001-11-04 05:57:16 +0000843/* Compare v to w. Return
844 -1 if v < w or exception (PyErr_Occurred() true in latter case).
845 0 if v == w.
846 1 if v > w.
847 XXX The docs (C API manual) say the return value is undefined in case
848 XXX of error.
849*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000850int
Fred Drake100814d2000-07-09 15:48:49 +0000851PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000852{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000853 int result;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000854
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000855 if (v == NULL || w == NULL) {
856 PyErr_BadInternalCall();
857 return -1;
858 }
859 if (v == w)
860 return 0;
861 if (Py_EnterRecursiveCall(" in cmp"))
862 return -1;
863 result = do_cmp(v, w);
864 Py_LeaveRecursiveCall();
865 return result < 0 ? -1 : result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000866}
867
Tim Petersc99213f2001-11-04 05:57:16 +0000868/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000869static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000870convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000871{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000872 PyObject *result;
873 switch (op) {
874 case Py_LT: c = c < 0; break;
875 case Py_LE: c = c <= 0; break;
876 case Py_EQ: c = c == 0; break;
877 case Py_NE: c = c != 0; break;
878 case Py_GT: c = c > 0; break;
879 case Py_GE: c = c >= 0; break;
880 }
881 result = c ? Py_True : Py_False;
882 Py_INCREF(result);
883 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884}
Tim Peters803526b2002-07-07 05:13:56 +0000885
Tim Petersc99213f2001-11-04 05:57:16 +0000886/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
887 Return
888 NULL if error
889 Py_True if v op w
890 Py_False if not (v op w)
891*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000892static PyObject *
893try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
894{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000895 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000896
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000897 c = try_3way_compare(v, w);
898 if (c >= 2) {
Steven Bethardae42f332008-03-18 17:26:10 +0000899
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000900 /* Py3K warning if types are not equal and comparison isn't == or != */
901 if (Py_Py3kWarningFlag &&
902 v->ob_type != w->ob_type && op != Py_EQ && op != Py_NE &&
903 PyErr_WarnEx(PyExc_DeprecationWarning,
904 "comparing unequal types not supported "
905 "in 3.x", 1) < 0) {
906 return NULL;
907 }
Steven Bethardae42f332008-03-18 17:26:10 +0000908
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000909 c = default_3way_compare(v, w);
910 }
911 if (c <= -2)
912 return NULL;
913 return convert_3way_to_object(op, c);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000914}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000915
Tim Petersc99213f2001-11-04 05:57:16 +0000916/* Do rich comparison on v and w. Return
917 NULL if error
918 Else a new reference to an object other than Py_NotImplemented, usually(?):
919 Py_True if v op w
920 Py_False if not (v op w)
921*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000922static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000923do_richcmp(PyObject *v, PyObject *w, int op)
924{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000925 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000926
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000927 res = try_rich_compare(v, w, op);
928 if (res != Py_NotImplemented)
929 return res;
930 Py_DECREF(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000931
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000932 return try_3way_to_rich_compare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000933}
934
Tim Petersc99213f2001-11-04 05:57:16 +0000935/* Return:
936 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000937 some object not equal to NotImplemented if it is implemented
938 (this latter object may not be a Boolean).
939*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000940PyObject *
941PyObject_RichCompare(PyObject *v, PyObject *w, int op)
942{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000943 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000944
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000945 assert(Py_LT <= op && op <= Py_GE);
946 if (Py_EnterRecursiveCall(" in cmp"))
947 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000948
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000949 /* If the types are equal, and not old-style instances, try to
950 get out cheap (don't bother with coercions etc.). */
951 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
952 cmpfunc fcmp;
953 richcmpfunc frich = RICHCOMPARE(v->ob_type);
954 /* If the type has richcmp, try it first. try_rich_compare
955 tries it two-sided, which is not needed since we've a
956 single type only. */
957 if (frich != NULL) {
958 res = (*frich)(v, w, op);
959 if (res != Py_NotImplemented)
960 goto Done;
961 Py_DECREF(res);
962 }
963 /* No richcmp, or this particular richmp not implemented.
964 Try 3-way cmp. */
965 fcmp = v->ob_type->tp_compare;
966 if (fcmp != NULL) {
967 int c = (*fcmp)(v, w);
968 c = adjust_tp_compare(c);
969 if (c == -2) {
970 res = NULL;
971 goto Done;
972 }
973 res = convert_3way_to_object(op, c);
974 goto Done;
975 }
976 }
Tim Peters67754e92001-11-04 07:29:31 +0000977
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000978 /* Fast path not taken, or couldn't deliver a useful result. */
979 res = do_richcmp(v, w, op);
Tim Peters67754e92001-11-04 07:29:31 +0000980Done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000981 Py_LeaveRecursiveCall();
982 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000983}
984
Tim Petersde9725f2001-05-05 10:06:17 +0000985/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000986int
987PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
988{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000989 PyObject *res;
990 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000991
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000992 /* Quick result when objects are the same.
993 Guarantees that identity implies equality. */
994 if (v == w) {
995 if (op == Py_EQ)
996 return 1;
997 else if (op == Py_NE)
998 return 0;
999 }
Raymond Hettinger93d44812004-03-21 17:01:44 +00001000
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001001 res = PyObject_RichCompare(v, w, op);
1002 if (res == NULL)
1003 return -1;
1004 if (PyBool_Check(res))
1005 ok = (res == Py_True);
1006 else
1007 ok = PyObject_IsTrue(res);
1008 Py_DECREF(res);
1009 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +00001010}
Fred Drake13634cf2000-06-29 19:17:04 +00001011
1012/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001013 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +00001014
1015 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1016*/
1017
1018long
Fred Drake100814d2000-07-09 15:48:49 +00001019_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001020{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001021 double intpart, fractpart;
1022 int expo;
1023 long hipart;
1024 long x; /* the final hash value */
1025 /* This is designed so that Python numbers of different types
1026 * that compare equal hash to the same value; otherwise comparisons
1027 * of mapping keys will turn out weird.
1028 */
Tim Peters39dce292000-08-15 03:34:48 +00001029
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001030 fractpart = modf(v, &intpart);
1031 if (fractpart == 0.0) {
1032 /* This must return the same hash as an equal int or long. */
1033 if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) {
1034 /* Convert to long and use its hash. */
1035 PyObject *plong; /* converted to Python long */
1036 if (Py_IS_INFINITY(intpart))
1037 /* can't convert to long int -- arbitrary */
1038 v = v < 0 ? -271828.0 : 314159.0;
1039 plong = PyLong_FromDouble(v);
1040 if (plong == NULL)
1041 return -1;
1042 x = PyObject_Hash(plong);
1043 Py_DECREF(plong);
1044 return x;
1045 }
1046 /* Fits in a C long == a Python int, so is its own hash. */
1047 x = (long)intpart;
1048 if (x == -1)
1049 x = -2;
1050 return x;
1051 }
1052 /* The fractional part is non-zero, so we don't have to worry about
1053 * making this match the hash of some other type.
1054 * Use frexp to get at the bits in the double.
1055 * Since the VAX D double format has 56 mantissa bits, which is the
1056 * most of any double format in use, each of these parts may have as
1057 * many as (but no more than) 56 significant bits.
1058 * So, assuming sizeof(long) >= 4, each part can be broken into two
1059 * longs; frexp and multiplication are used to do that.
1060 * Also, since the Cray double format has 15 exponent bits, which is
1061 * the most of any double format in use, shifting the exponent field
1062 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
1063 */
1064 v = frexp(v, &expo);
1065 v *= 2147483648.0; /* 2**31 */
1066 hipart = (long)v; /* take the top 32 bits */
1067 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1068 x = hipart + (long)v + (expo << 15);
1069 if (x == -1)
1070 x = -2;
1071 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001072}
1073
1074long
Fred Drake100814d2000-07-09 15:48:49 +00001075_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001076{
1077#if SIZEOF_LONG >= SIZEOF_VOID_P
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001078 return (long)p;
Fred Drake13634cf2000-06-29 19:17:04 +00001079#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001080 /* convert to a Python long and hash that */
1081 PyObject* longobj;
1082 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001083
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001084 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1085 x = -1;
1086 goto finally;
1087 }
1088 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001089
Fred Drake13634cf2000-06-29 19:17:04 +00001090finally:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001091 Py_XDECREF(longobj);
1092 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001093#endif
1094}
1095
Nick Coghlan53663a62008-07-15 14:27:37 +00001096long
1097PyObject_HashNotImplemented(PyObject *self)
1098{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001099 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1100 self->ob_type->tp_name);
1101 return -1;
Nick Coghlan53663a62008-07-15 14:27:37 +00001102}
Fred Drake13634cf2000-06-29 19:17:04 +00001103
Barry Warsaw1e13eb02012-02-20 20:42:21 -05001104_Py_HashSecret_t _Py_HashSecret;
1105
Guido van Rossum9bfef441993-03-29 10:43:31 +00001106long
Fred Drake100814d2000-07-09 15:48:49 +00001107PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001108{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001109 PyTypeObject *tp = v->ob_type;
1110 if (tp->tp_hash != NULL)
1111 return (*tp->tp_hash)(v);
1112 /* To keep to the general practice that inheriting
1113 * solely from object in C code should work without
1114 * an explicit call to PyType_Ready, we implicitly call
1115 * PyType_Ready here and then check the tp_hash slot again
1116 */
1117 if (tp->tp_dict == NULL) {
1118 if (PyType_Ready(tp) < 0)
1119 return -1;
1120 if (tp->tp_hash != NULL)
1121 return (*tp->tp_hash)(v);
1122 }
1123 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
1124 return _Py_HashPointer(v); /* Use address as hash value */
1125 }
1126 /* If there's a cmp but no hash defined, the object can't be hashed */
1127 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001128}
1129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001130PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001131PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001132{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001133 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001134
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001135 if (Py_TYPE(v)->tp_getattr != NULL)
1136 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1137 w = PyString_InternFromString(name);
1138 if (w == NULL)
1139 return NULL;
1140 res = PyObject_GetAttr(v, w);
1141 Py_XDECREF(w);
1142 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001143}
1144
1145int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001146PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001147{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001148 PyObject *res = PyObject_GetAttrString(v, name);
1149 if (res != NULL) {
1150 Py_DECREF(res);
1151 return 1;
1152 }
1153 PyErr_Clear();
1154 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001155}
1156
1157int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001158PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001159{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001160 PyObject *s;
1161 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001162
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001163 if (Py_TYPE(v)->tp_setattr != NULL)
1164 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1165 s = PyString_InternFromString(name);
1166 if (s == NULL)
1167 return -1;
1168 res = PyObject_SetAttr(v, s, w);
1169 Py_XDECREF(s);
1170 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001171}
1172
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001173PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001174PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001175{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001176 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001178 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001179#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001180 /* The Unicode to string conversion is done here because the
1181 existing tp_getattro slots expect a string object as name
1182 and we wouldn't want to break those. */
1183 if (PyUnicode_Check(name)) {
1184 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1185 if (name == NULL)
1186 return NULL;
1187 }
1188 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001189#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001190 {
1191 PyErr_Format(PyExc_TypeError,
1192 "attribute name must be string, not '%.200s'",
1193 Py_TYPE(name)->tp_name);
1194 return NULL;
1195 }
1196 }
1197 if (tp->tp_getattro != NULL)
1198 return (*tp->tp_getattro)(v, name);
1199 if (tp->tp_getattr != NULL)
1200 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1201 PyErr_Format(PyExc_AttributeError,
1202 "'%.50s' object has no attribute '%.400s'",
1203 tp->tp_name, PyString_AS_STRING(name));
1204 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001205}
1206
1207int
Fred Drake100814d2000-07-09 15:48:49 +00001208PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001209{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001210 PyObject *res = PyObject_GetAttr(v, name);
1211 if (res != NULL) {
1212 Py_DECREF(res);
1213 return 1;
1214 }
1215 PyErr_Clear();
1216 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001217}
1218
1219int
Fred Drake100814d2000-07-09 15:48:49 +00001220PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001221{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001222 PyTypeObject *tp = Py_TYPE(v);
1223 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001224
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001225 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001226#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001227 /* The Unicode to string conversion is done here because the
1228 existing tp_setattro slots expect a string object as name
1229 and we wouldn't want to break those. */
1230 if (PyUnicode_Check(name)) {
1231 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1232 if (name == NULL)
1233 return -1;
1234 }
1235 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001236#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001237 {
1238 PyErr_Format(PyExc_TypeError,
1239 "attribute name must be string, not '%.200s'",
1240 Py_TYPE(name)->tp_name);
1241 return -1;
1242 }
1243 }
1244 else
1245 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001247 PyString_InternInPlace(&name);
1248 if (tp->tp_setattro != NULL) {
1249 err = (*tp->tp_setattro)(v, name, value);
1250 Py_DECREF(name);
1251 return err;
1252 }
1253 if (tp->tp_setattr != NULL) {
1254 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1255 Py_DECREF(name);
1256 return err;
1257 }
1258 Py_DECREF(name);
1259 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1260 PyErr_Format(PyExc_TypeError,
1261 "'%.100s' object has no attributes "
1262 "(%s .%.100s)",
1263 tp->tp_name,
1264 value==NULL ? "del" : "assign to",
1265 PyString_AS_STRING(name));
1266 else
1267 PyErr_Format(PyExc_TypeError,
1268 "'%.100s' object has only read-only attributes "
1269 "(%s .%.100s)",
1270 tp->tp_name,
1271 value==NULL ? "del" : "assign to",
1272 PyString_AS_STRING(name));
1273 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274}
1275
1276/* Helper to get a pointer to an object's __dict__ slot, if any */
1277
1278PyObject **
1279_PyObject_GetDictPtr(PyObject *obj)
1280{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001281 Py_ssize_t dictoffset;
1282 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001284 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1285 return NULL;
1286 dictoffset = tp->tp_dictoffset;
1287 if (dictoffset == 0)
1288 return NULL;
1289 if (dictoffset < 0) {
1290 Py_ssize_t tsize;
1291 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001292
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001293 tsize = ((PyVarObject *)obj)->ob_size;
1294 if (tsize < 0)
1295 tsize = -tsize;
1296 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001297
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001298 dictoffset += (long)size;
1299 assert(dictoffset > 0);
1300 assert(dictoffset % SIZEOF_VOID_P == 0);
1301 }
1302 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303}
1304
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001306PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001307{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001308 Py_INCREF(obj);
1309 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001310}
1311
Michael W. Hudson1593f502004-09-14 17:09:47 +00001312/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1313
Raymond Hettinger01538262003-03-17 08:24:35 +00001314PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1316{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001317 PyTypeObject *tp = Py_TYPE(obj);
1318 PyObject *descr = NULL;
1319 PyObject *res = NULL;
1320 descrgetfunc f;
1321 Py_ssize_t dictoffset;
1322 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001324 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001325#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001326 /* The Unicode to string conversion is done here because the
1327 existing tp_setattro slots expect a string object as name
1328 and we wouldn't want to break those. */
1329 if (PyUnicode_Check(name)) {
1330 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1331 if (name == NULL)
1332 return NULL;
1333 }
1334 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001335#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001336 {
1337 PyErr_Format(PyExc_TypeError,
1338 "attribute name must be string, not '%.200s'",
1339 Py_TYPE(name)->tp_name);
1340 return NULL;
1341 }
1342 }
1343 else
1344 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001345
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001346 if (tp->tp_dict == NULL) {
1347 if (PyType_Ready(tp) < 0)
1348 goto done;
1349 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001351#if 0 /* XXX this is not quite _PyType_Lookup anymore */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001352 /* Inline _PyType_Lookup */
1353 {
1354 Py_ssize_t i, n;
1355 PyObject *mro, *base, *dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001356
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001357 /* Look in tp_dict of types in MRO */
1358 mro = tp->tp_mro;
1359 assert(mro != NULL);
1360 assert(PyTuple_Check(mro));
1361 n = PyTuple_GET_SIZE(mro);
1362 for (i = 0; i < n; i++) {
1363 base = PyTuple_GET_ITEM(mro, i);
1364 if (PyClass_Check(base))
1365 dict = ((PyClassObject *)base)->cl_dict;
1366 else {
1367 assert(PyType_Check(base));
1368 dict = ((PyTypeObject *)base)->tp_dict;
1369 }
1370 assert(dict && PyDict_Check(dict));
1371 descr = PyDict_GetItem(dict, name);
1372 if (descr != NULL)
1373 break;
1374 }
1375 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001376#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001377 descr = _PyType_Lookup(tp, name);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001378#endif
Guido van Rossum056fbf42002-08-19 19:22:50 +00001379
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001380 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001381
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001382 f = NULL;
1383 if (descr != NULL &&
1384 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1385 f = descr->ob_type->tp_descr_get;
1386 if (f != NULL && PyDescr_IsData(descr)) {
1387 res = f(descr, obj, (PyObject *)obj->ob_type);
1388 Py_DECREF(descr);
1389 goto done;
1390 }
1391 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001393 /* Inline _PyObject_GetDictPtr */
1394 dictoffset = tp->tp_dictoffset;
1395 if (dictoffset != 0) {
1396 PyObject *dict;
1397 if (dictoffset < 0) {
1398 Py_ssize_t tsize;
1399 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001400
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001401 tsize = ((PyVarObject *)obj)->ob_size;
1402 if (tsize < 0)
1403 tsize = -tsize;
1404 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001405
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001406 dictoffset += (long)size;
1407 assert(dictoffset > 0);
1408 assert(dictoffset % SIZEOF_VOID_P == 0);
1409 }
1410 dictptr = (PyObject **) ((char *)obj + dictoffset);
1411 dict = *dictptr;
1412 if (dict != NULL) {
1413 Py_INCREF(dict);
1414 res = PyDict_GetItem(dict, name);
1415 if (res != NULL) {
1416 Py_INCREF(res);
1417 Py_XDECREF(descr);
1418 Py_DECREF(dict);
1419 goto done;
1420 }
1421 Py_DECREF(dict);
1422 }
1423 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001425 if (f != NULL) {
1426 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1427 Py_DECREF(descr);
1428 goto done;
1429 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001430
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001431 if (descr != NULL) {
1432 res = descr;
1433 /* descr was already increfed above */
1434 goto done;
1435 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001436
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001437 PyErr_Format(PyExc_AttributeError,
1438 "'%.50s' object has no attribute '%.400s'",
1439 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001440 done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001441 Py_DECREF(name);
1442 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001443}
1444
1445int
1446PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1447{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001448 PyTypeObject *tp = Py_TYPE(obj);
1449 PyObject *descr;
1450 descrsetfunc f;
1451 PyObject **dictptr;
1452 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001453
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001454 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001455#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001456 /* The Unicode to string conversion is done here because the
1457 existing tp_setattro slots expect a string object as name
1458 and we wouldn't want to break those. */
1459 if (PyUnicode_Check(name)) {
1460 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1461 if (name == NULL)
1462 return -1;
1463 }
1464 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001465#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001466 {
1467 PyErr_Format(PyExc_TypeError,
1468 "attribute name must be string, not '%.200s'",
1469 Py_TYPE(name)->tp_name);
1470 return -1;
1471 }
1472 }
1473 else
1474 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001475
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001476 if (tp->tp_dict == NULL) {
1477 if (PyType_Ready(tp) < 0)
1478 goto done;
1479 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001480
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001481 descr = _PyType_Lookup(tp, name);
1482 f = NULL;
1483 if (descr != NULL &&
1484 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1485 f = descr->ob_type->tp_descr_set;
1486 if (f != NULL && PyDescr_IsData(descr)) {
1487 res = f(descr, obj, value);
1488 goto done;
1489 }
1490 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001491
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001492 dictptr = _PyObject_GetDictPtr(obj);
1493 if (dictptr != NULL) {
1494 PyObject *dict = *dictptr;
1495 if (dict == NULL && value != NULL) {
1496 dict = PyDict_New();
1497 if (dict == NULL)
1498 goto done;
1499 *dictptr = dict;
1500 }
1501 if (dict != NULL) {
1502 Py_INCREF(dict);
1503 if (value == NULL)
1504 res = PyDict_DelItem(dict, name);
1505 else
1506 res = PyDict_SetItem(dict, name, value);
1507 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1508 PyErr_SetObject(PyExc_AttributeError, name);
1509 Py_DECREF(dict);
1510 goto done;
1511 }
1512 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001513
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001514 if (f != NULL) {
1515 res = f(descr, obj, value);
1516 goto done;
1517 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001518
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001519 if (descr == NULL) {
1520 PyErr_Format(PyExc_AttributeError,
1521 "'%.100s' object has no attribute '%.200s'",
1522 tp->tp_name, PyString_AS_STRING(name));
1523 goto done;
1524 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001525
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001526 PyErr_Format(PyExc_AttributeError,
1527 "'%.50s' object attribute '%.400s' is read-only",
1528 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001529 done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001530 Py_DECREF(name);
1531 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001532}
1533
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001534/* Test a value used as condition, e.g., in a for or if statement.
1535 Return -1 if an error occurred */
1536
1537int
Fred Drake100814d2000-07-09 15:48:49 +00001538PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001539{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001540 Py_ssize_t res;
1541 if (v == Py_True)
1542 return 1;
1543 if (v == Py_False)
1544 return 0;
1545 if (v == Py_None)
1546 return 0;
1547 else if (v->ob_type->tp_as_number != NULL &&
1548 v->ob_type->tp_as_number->nb_nonzero != NULL)
1549 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
1550 else if (v->ob_type->tp_as_mapping != NULL &&
1551 v->ob_type->tp_as_mapping->mp_length != NULL)
1552 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1553 else if (v->ob_type->tp_as_sequence != NULL &&
1554 v->ob_type->tp_as_sequence->sq_length != NULL)
1555 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1556 else
1557 return 1;
1558 /* if it is negative, it should be either -1 or -2 */
1559 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001560}
1561
Tim Peters803526b2002-07-07 05:13:56 +00001562/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001563 Return -1 if an error occurred */
1564
1565int
Fred Drake100814d2000-07-09 15:48:49 +00001566PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001567{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001568 int res;
1569 res = PyObject_IsTrue(v);
1570 if (res < 0)
1571 return res;
1572 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001573}
1574
Guido van Rossum5524a591995-01-10 15:26:20 +00001575/* Coerce two numeric types to the "larger" one.
1576 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001577 Return value:
1578 -1 if an error occurred;
1579 0 if the coercion succeeded (and then the reference counts are increased);
1580 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001581*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001582int
Fred Drake100814d2000-07-09 15:48:49 +00001583PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001584{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001585 register PyObject *v = *pv;
1586 register PyObject *w = *pw;
1587 int res;
Guido van Rossum5524a591995-01-10 15:26:20 +00001588
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001589 /* Shortcut only for old-style types */
1590 if (v->ob_type == w->ob_type &&
1591 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1592 {
1593 Py_INCREF(v);
1594 Py_INCREF(w);
1595 return 0;
1596 }
1597 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1598 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1599 if (res <= 0)
1600 return res;
1601 }
1602 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1603 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1604 if (res <= 0)
1605 return res;
1606 }
1607 return 1;
Guido van Rossum242c6421997-11-19 16:03:17 +00001608}
1609
Guido van Rossume797ec12001-01-17 15:24:28 +00001610/* Coerce two numeric types to the "larger" one.
1611 Increment the reference count on each argument.
1612 Return -1 and raise an exception if no coercion is possible
1613 (and then no reference count is incremented).
1614*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001615int
Fred Drake100814d2000-07-09 15:48:49 +00001616PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001617{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001618 int err = PyNumber_CoerceEx(pv, pw);
1619 if (err <= 0)
1620 return err;
1621 PyErr_SetString(PyExc_TypeError, "number coercion failed");
1622 return -1;
Guido van Rossum5524a591995-01-10 15:26:20 +00001623}
1624
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001625
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001626/* Test whether an object can be called */
1627
1628int
Fred Drake100814d2000-07-09 15:48:49 +00001629PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001630{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001631 if (x == NULL)
1632 return 0;
1633 if (PyInstance_Check(x)) {
1634 PyObject *call = PyObject_GetAttrString(x, "__call__");
1635 if (call == NULL) {
1636 PyErr_Clear();
1637 return 0;
1638 }
1639 /* Could test recursively but don't, for fear of endless
1640 recursion if some joker sets self.__call__ = self */
1641 Py_DECREF(call);
1642 return 1;
1643 }
1644 else {
1645 return x->ob_type->tp_call != NULL;
1646 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001647}
1648
Georg Brandl871f1bc2007-03-12 13:17:36 +00001649/* ------------------------- PyObject_Dir() helpers ------------------------- */
1650
Tim Peters7eea37e2001-09-04 22:08:56 +00001651/* Helper for PyObject_Dir.
1652 Merge the __dict__ of aclass into dict, and recursively also all
1653 the __dict__s of aclass's base classes. The order of merging isn't
1654 defined, as it's expected that only the final set of dict keys is
1655 interesting.
1656 Return 0 on success, -1 on error.
1657*/
1658
1659static int
1660merge_class_dict(PyObject* dict, PyObject* aclass)
1661{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001662 PyObject *classdict;
1663 PyObject *bases;
Tim Peters7eea37e2001-09-04 22:08:56 +00001664
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001665 assert(PyDict_Check(dict));
1666 assert(aclass);
Tim Peters7eea37e2001-09-04 22:08:56 +00001667
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001668 /* Merge in the type's dict (if any). */
1669 classdict = PyObject_GetAttrString(aclass, "__dict__");
1670 if (classdict == NULL)
1671 PyErr_Clear();
1672 else {
1673 int status = PyDict_Update(dict, classdict);
1674 Py_DECREF(classdict);
1675 if (status < 0)
1676 return -1;
1677 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001678
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001679 /* Recursively merge in the base types' (if any) dicts. */
1680 bases = PyObject_GetAttrString(aclass, "__bases__");
1681 if (bases == NULL)
1682 PyErr_Clear();
1683 else {
1684 /* We have no guarantee that bases is a real tuple */
1685 Py_ssize_t i, n;
1686 n = PySequence_Size(bases); /* This better be right */
1687 if (n < 0)
1688 PyErr_Clear();
1689 else {
1690 for (i = 0; i < n; i++) {
1691 int status;
1692 PyObject *base = PySequence_GetItem(bases, i);
1693 if (base == NULL) {
1694 Py_DECREF(bases);
1695 return -1;
1696 }
1697 status = merge_class_dict(dict, base);
1698 Py_DECREF(base);
1699 if (status < 0) {
1700 Py_DECREF(bases);
1701 return -1;
1702 }
1703 }
1704 }
1705 Py_DECREF(bases);
1706 }
1707 return 0;
Tim Peters7eea37e2001-09-04 22:08:56 +00001708}
1709
Tim Peters305b5852001-09-17 02:38:46 +00001710/* Helper for PyObject_Dir.
1711 If obj has an attr named attrname that's a list, merge its string
1712 elements into keys of dict.
1713 Return 0 on success, -1 on error. Errors due to not finding the attr,
1714 or the attr not being a list, are suppressed.
1715*/
1716
1717static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001718merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001719{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001720 PyObject *list;
1721 int result = 0;
Tim Peters305b5852001-09-17 02:38:46 +00001722
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001723 assert(PyDict_Check(dict));
1724 assert(obj);
1725 assert(attrname);
Tim Peters305b5852001-09-17 02:38:46 +00001726
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001727 list = PyObject_GetAttrString(obj, attrname);
1728 if (list == NULL)
1729 PyErr_Clear();
Tim Peters305b5852001-09-17 02:38:46 +00001730
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001731 else if (PyList_Check(list)) {
1732 int i;
1733 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1734 PyObject *item = PyList_GET_ITEM(list, i);
1735 if (PyString_Check(item)) {
1736 result = PyDict_SetItem(dict, item, Py_None);
1737 if (result < 0)
1738 break;
1739 }
1740 }
1741 if (Py_Py3kWarningFlag &&
1742 (strcmp(attrname, "__members__") == 0 ||
1743 strcmp(attrname, "__methods__") == 0)) {
1744 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1745 "__members__ and __methods__ not "
1746 "supported in 3.x", 1) < 0) {
1747 Py_XDECREF(list);
1748 return -1;
1749 }
1750 }
1751 }
Tim Peters305b5852001-09-17 02:38:46 +00001752
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001753 Py_XDECREF(list);
1754 return result;
Tim Peters305b5852001-09-17 02:38:46 +00001755}
1756
Georg Brandl871f1bc2007-03-12 13:17:36 +00001757/* Helper for PyObject_Dir without arguments: returns the local scope. */
1758static PyObject *
Jeremy Hylton26ca9252007-03-16 14:49:11 +00001759_dir_locals(void)
Tim Peters7eea37e2001-09-04 22:08:56 +00001760{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001761 PyObject *names;
1762 PyObject *locals = PyEval_GetLocals();
Tim Peters7eea37e2001-09-04 22:08:56 +00001763
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001764 if (locals == NULL) {
1765 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1766 return NULL;
1767 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001768
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001769 names = PyMapping_Keys(locals);
1770 if (!names)
1771 return NULL;
1772 if (!PyList_Check(names)) {
1773 PyErr_Format(PyExc_TypeError,
1774 "dir(): expected keys() of locals to be a list, "
1775 "not '%.200s'", Py_TYPE(names)->tp_name);
1776 Py_DECREF(names);
1777 return NULL;
1778 }
1779 /* the locals don't need to be DECREF'd */
1780 return names;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001781}
Tim Peters7eea37e2001-09-04 22:08:56 +00001782
Georg Brandl871f1bc2007-03-12 13:17:36 +00001783/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001784 We deliberately don't suck up its __class__, as methods belonging to the
1785 metaclass would probably be more confusing than helpful.
Georg Brandl871f1bc2007-03-12 13:17:36 +00001786*/
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001787static PyObject *
Georg Brandl871f1bc2007-03-12 13:17:36 +00001788_specialized_dir_type(PyObject *obj)
1789{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001790 PyObject *result = NULL;
1791 PyObject *dict = PyDict_New();
Georg Brandl871f1bc2007-03-12 13:17:36 +00001792
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001793 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1794 result = PyDict_Keys(dict);
Georg Brandl871f1bc2007-03-12 13:17:36 +00001795
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001796 Py_XDECREF(dict);
1797 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001798}
1799
1800/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1801static PyObject *
1802_specialized_dir_module(PyObject *obj)
1803{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001804 PyObject *result = NULL;
1805 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Georg Brandl871f1bc2007-03-12 13:17:36 +00001806
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001807 if (dict != NULL) {
1808 if (PyDict_Check(dict))
1809 result = PyDict_Keys(dict);
1810 else {
1811 char *name = PyModule_GetName(obj);
1812 if (name)
1813 PyErr_Format(PyExc_TypeError,
1814 "%.200s.__dict__ is not a dictionary",
1815 name);
1816 }
1817 }
Georg Brandl871f1bc2007-03-12 13:17:36 +00001818
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001819 Py_XDECREF(dict);
1820 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001821}
1822
1823/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1824 and recursively up the __class__.__bases__ chain.
1825*/
1826static PyObject *
1827_generic_dir(PyObject *obj)
1828{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001829 PyObject *result = NULL;
1830 PyObject *dict = NULL;
1831 PyObject *itsclass = NULL;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001832
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001833 /* Get __dict__ (which may or may not be a real dict...) */
1834 dict = PyObject_GetAttrString(obj, "__dict__");
1835 if (dict == NULL) {
1836 PyErr_Clear();
1837 dict = PyDict_New();
1838 }
1839 else if (!PyDict_Check(dict)) {
1840 Py_DECREF(dict);
1841 dict = PyDict_New();
1842 }
1843 else {
1844 /* Copy __dict__ to avoid mutating it. */
1845 PyObject *temp = PyDict_Copy(dict);
1846 Py_DECREF(dict);
1847 dict = temp;
1848 }
Georg Brandl871f1bc2007-03-12 13:17:36 +00001849
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001850 if (dict == NULL)
1851 goto error;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001852
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001853 /* Merge in __members__ and __methods__ (if any).
1854 * This is removed in Python 3000. */
1855 if (merge_list_attr(dict, obj, "__members__") < 0)
1856 goto error;
1857 if (merge_list_attr(dict, obj, "__methods__") < 0)
1858 goto error;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001859
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001860 /* Merge in attrs reachable from its class. */
1861 itsclass = PyObject_GetAttrString(obj, "__class__");
1862 if (itsclass == NULL)
1863 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1864 __class__ exists? */
1865 PyErr_Clear();
1866 else {
1867 if (merge_class_dict(dict, itsclass) != 0)
1868 goto error;
1869 }
1870
1871 result = PyDict_Keys(dict);
1872 /* fall through */
Georg Brandl871f1bc2007-03-12 13:17:36 +00001873error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001874 Py_XDECREF(itsclass);
1875 Py_XDECREF(dict);
1876 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001877}
1878
1879/* Helper for PyObject_Dir: object introspection.
1880 This calls one of the above specialized versions if no __dir__ method
1881 exists. */
1882static PyObject *
1883_dir_object(PyObject *obj)
1884{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001885 PyObject *result = NULL;
1886 PyObject *dirfunc = PyObject_GetAttrString((PyObject *)obj->ob_type,
1887 "__dir__");
Georg Brandl871f1bc2007-03-12 13:17:36 +00001888
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001889 assert(obj);
1890 if (dirfunc == NULL) {
1891 /* use default implementation */
1892 PyErr_Clear();
1893 if (PyModule_Check(obj))
1894 result = _specialized_dir_module(obj);
1895 else if (PyType_Check(obj) || PyClass_Check(obj))
1896 result = _specialized_dir_type(obj);
1897 else
1898 result = _generic_dir(obj);
1899 }
1900 else {
1901 /* use __dir__ */
1902 result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
1903 Py_DECREF(dirfunc);
1904 if (result == NULL)
1905 return NULL;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001906
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001907 /* result must be a list */
1908 /* XXX(gbrandl): could also check if all items are strings */
1909 if (!PyList_Check(result)) {
1910 PyErr_Format(PyExc_TypeError,
1911 "__dir__() must return a list, not %.200s",
1912 Py_TYPE(result)->tp_name);
1913 Py_DECREF(result);
1914 result = NULL;
1915 }
1916 }
Georg Brandl871f1bc2007-03-12 13:17:36 +00001917
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001918 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001919}
1920
1921/* Implementation of dir() -- if obj is NULL, returns the names in the current
1922 (local) scope. Otherwise, performs introspection of the object: returns a
1923 sorted list of attribute names (supposedly) accessible from the object
1924*/
1925PyObject *
1926PyObject_Dir(PyObject *obj)
1927{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001928 PyObject * result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001929
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001930 if (obj == NULL)
1931 /* no object -- introspect the locals */
1932 result = _dir_locals();
1933 else
1934 /* object -- introspect the object */
1935 result = _dir_object(obj);
Georg Brandl871f1bc2007-03-12 13:17:36 +00001936
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001937 assert(result == NULL || PyList_Check(result));
Georg Brandl871f1bc2007-03-12 13:17:36 +00001938
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001939 if (result != NULL && PyList_Sort(result) != 0) {
1940 /* sorting the list failed */
1941 Py_DECREF(result);
1942 result = NULL;
1943 }
1944
1945 return result;
Tim Peters7eea37e2001-09-04 22:08:56 +00001946}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001947
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001948/*
1949NoObject is usable as a non-NULL undefined value, used by the macro None.
1950There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001951so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001952(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001953*/
1954
Guido van Rossum0c182a11992-03-27 17:26:13 +00001955/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001956static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001957none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001958{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001959 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001960}
1961
Barry Warsaw9bf16442001-01-23 16:24:35 +00001962/* ARGUSED */
1963static void
Tim Peters803526b2002-07-07 05:13:56 +00001964none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001965{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001966 /* This should never get called, but we also don't want to SEGV if
1967 * we accidentally decref None out of existence.
1968 */
1969 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001970}
1971
1972
Guido van Rossumba21a492001-08-16 08:17:26 +00001973static PyTypeObject PyNone_Type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001974 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1975 "NoneType",
1976 0,
1977 0,
1978 none_dealloc, /*tp_dealloc*/ /*never called*/
1979 0, /*tp_print*/
1980 0, /*tp_getattr*/
1981 0, /*tp_setattr*/
1982 0, /*tp_compare*/
1983 none_repr, /*tp_repr*/
1984 0, /*tp_as_number*/
1985 0, /*tp_as_sequence*/
1986 0, /*tp_as_mapping*/
1987 (hashfunc)_Py_HashPointer, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001988};
1989
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001990PyObject _Py_NoneStruct = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001991 _PyObject_EXTRA_INIT
1992 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001993};
1994
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001995/* NotImplemented is an object that can be used to signal that an
1996 operation is not implemented for the given type combination. */
1997
1998static PyObject *
1999NotImplemented_repr(PyObject *op)
2000{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002001 return PyString_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00002002}
2003
2004static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002005 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2006 "NotImplementedType",
2007 0,
2008 0,
2009 none_dealloc, /*tp_dealloc*/ /*never called*/
2010 0, /*tp_print*/
2011 0, /*tp_getattr*/
2012 0, /*tp_setattr*/
2013 0, /*tp_compare*/
2014 NotImplemented_repr, /*tp_repr*/
2015 0, /*tp_as_number*/
2016 0, /*tp_as_sequence*/
2017 0, /*tp_as_mapping*/
2018 0, /*tp_hash */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00002019};
2020
2021PyObject _Py_NotImplementedStruct = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002022 _PyObject_EXTRA_INIT
2023 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00002024};
2025
Guido van Rossumba21a492001-08-16 08:17:26 +00002026void
2027_Py_ReadyTypes(void)
2028{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002029 if (PyType_Ready(&PyType_Type) < 0)
2030 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002031
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002032 if (PyType_Ready(&_PyWeakref_RefType) < 0)
2033 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00002034
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002035 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
2036 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002037
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002038 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
2039 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002040
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002041 if (PyType_Ready(&PyBool_Type) < 0)
2042 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00002043
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002044 if (PyType_Ready(&PyString_Type) < 0)
2045 Py_FatalError("Can't initialize str type");
Guido van Rossumcacfc072002-05-24 19:01:59 +00002046
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002047 if (PyType_Ready(&PyByteArray_Type) < 0)
2048 Py_FatalError("Can't initialize bytearray type");
Christian Heimes1a6387e2008-03-26 12:49:49 +00002049
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002050 if (PyType_Ready(&PyList_Type) < 0)
2051 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002052
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002053 if (PyType_Ready(&PyNone_Type) < 0)
2054 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002055
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002056 if (PyType_Ready(&PyNotImplemented_Type) < 0)
2057 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002058
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002059 if (PyType_Ready(&PyTraceBack_Type) < 0)
2060 Py_FatalError("Can't initialize traceback type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002061
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002062 if (PyType_Ready(&PySuper_Type) < 0)
2063 Py_FatalError("Can't initialize super type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002064
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002065 if (PyType_Ready(&PyBaseObject_Type) < 0)
2066 Py_FatalError("Can't initialize object type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002067
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002068 if (PyType_Ready(&PyRange_Type) < 0)
2069 Py_FatalError("Can't initialize xrange type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002070
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002071 if (PyType_Ready(&PyDict_Type) < 0)
2072 Py_FatalError("Can't initialize dict type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002073
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002074 if (PyType_Ready(&PySet_Type) < 0)
2075 Py_FatalError("Can't initialize set type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002076
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002077 if (PyType_Ready(&PyUnicode_Type) < 0)
2078 Py_FatalError("Can't initialize unicode type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002079
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002080 if (PyType_Ready(&PySlice_Type) < 0)
2081 Py_FatalError("Can't initialize slice type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002082
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002083 if (PyType_Ready(&PyStaticMethod_Type) < 0)
2084 Py_FatalError("Can't initialize static method type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002085
Benjamin Petersonc4853612009-04-20 02:09:13 +00002086#ifndef WITHOUT_COMPLEX
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002087 if (PyType_Ready(&PyComplex_Type) < 0)
2088 Py_FatalError("Can't initialize complex type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002089#endif
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002090
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002091 if (PyType_Ready(&PyFloat_Type) < 0)
2092 Py_FatalError("Can't initialize float type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002093
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002094 if (PyType_Ready(&PyBuffer_Type) < 0)
2095 Py_FatalError("Can't initialize buffer type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002096
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002097 if (PyType_Ready(&PyLong_Type) < 0)
2098 Py_FatalError("Can't initialize long type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002099
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002100 if (PyType_Ready(&PyInt_Type) < 0)
2101 Py_FatalError("Can't initialize int type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002102
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002103 if (PyType_Ready(&PyFrozenSet_Type) < 0)
2104 Py_FatalError("Can't initialize frozenset type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002105
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002106 if (PyType_Ready(&PyProperty_Type) < 0)
2107 Py_FatalError("Can't initialize property type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002108
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002109 if (PyType_Ready(&PyTuple_Type) < 0)
2110 Py_FatalError("Can't initialize tuple type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002111
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002112 if (PyType_Ready(&PyEnum_Type) < 0)
2113 Py_FatalError("Can't initialize enumerate type");
Benjamin Peterson4585ca92009-04-18 20:50:24 +00002114
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002115 if (PyType_Ready(&PyReversed_Type) < 0)
2116 Py_FatalError("Can't initialize reversed type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002117
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002118 if (PyType_Ready(&PyCode_Type) < 0)
2119 Py_FatalError("Can't initialize code type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002120
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002121 if (PyType_Ready(&PyFrame_Type) < 0)
2122 Py_FatalError("Can't initialize frame type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002123
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002124 if (PyType_Ready(&PyCFunction_Type) < 0)
2125 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002126
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002127 if (PyType_Ready(&PyMethod_Type) < 0)
2128 Py_FatalError("Can't initialize method type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002129
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002130 if (PyType_Ready(&PyFunction_Type) < 0)
2131 Py_FatalError("Can't initialize function type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002132
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002133 if (PyType_Ready(&PyClass_Type) < 0)
2134 Py_FatalError("Can't initialize class type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002135
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002136 if (PyType_Ready(&PyDictProxy_Type) < 0)
2137 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002138
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002139 if (PyType_Ready(&PyGen_Type) < 0)
2140 Py_FatalError("Can't initialize generator type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002141
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002142 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
2143 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002144
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002145 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
2146 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002147
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002148 if (PyType_Ready(&PyInstance_Type) < 0)
2149 Py_FatalError("Can't initialize instance type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002150
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002151 if (PyType_Ready(&PyEllipsis_Type) < 0)
2152 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonc4853612009-04-20 02:09:13 +00002153
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002154 if (PyType_Ready(&PyMemberDescr_Type) < 0)
2155 Py_FatalError("Can't initialize member descriptor type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002156}
2157
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002158
Guido van Rossum84a90321996-05-22 16:34:47 +00002159#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002160
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002161void
Fred Drake100814d2000-07-09 15:48:49 +00002162_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002163{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002164 _Py_INC_REFTOTAL;
2165 op->ob_refcnt = 1;
2166 _Py_AddToAllObjects(op, 1);
2167 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002168}
2169
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002170void
Fred Drake100814d2000-07-09 15:48:49 +00002171_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002172{
Guido van Rossumbffd6832000-01-20 22:32:56 +00002173#ifdef SLOW_UNREF_CHECK
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002174 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00002175#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002176 if (op->ob_refcnt < 0)
2177 Py_FatalError("UNREF negative refcnt");
2178 if (op == &refchain ||
2179 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
2180 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002181#ifdef SLOW_UNREF_CHECK
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002182 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
2183 if (p == op)
2184 break;
2185 }
2186 if (p == &refchain) /* Not found */
2187 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002188#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002189 op->_ob_next->_ob_prev = op->_ob_prev;
2190 op->_ob_prev->_ob_next = op->_ob_next;
2191 op->_ob_next = op->_ob_prev = NULL;
2192 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002193}
2194
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002195void
Fred Drake100814d2000-07-09 15:48:49 +00002196_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002197{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002198 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2199 _Py_ForgetReference(op);
2200 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002201}
2202
Tim Peters269b2a62003-04-17 19:52:29 +00002203/* Print all live objects. Because PyObject_Print is called, the
2204 * interpreter must be in a healthy state.
2205 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002206void
Fred Drake100814d2000-07-09 15:48:49 +00002207_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002208{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002209 PyObject *op;
2210 fprintf(fp, "Remaining objects:\n");
2211 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
2212 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
2213 if (PyObject_Print(op, fp, 0) != 0)
2214 PyErr_Clear();
2215 putc('\n', fp);
2216 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002217}
2218
Tim Peters269b2a62003-04-17 19:52:29 +00002219/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
2220 * doesn't make any calls to the Python C API, so is always safe to call.
2221 */
2222void
2223_Py_PrintReferenceAddresses(FILE *fp)
2224{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002225 PyObject *op;
2226 fprintf(fp, "Remaining object addresses:\n");
2227 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
2228 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
2229 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00002230}
2231
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002232PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002233_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002234{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002235 int i, n;
2236 PyObject *t = NULL;
2237 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002238
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002239 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2240 return NULL;
2241 op = refchain._ob_next;
2242 res = PyList_New(0);
2243 if (res == NULL)
2244 return NULL;
2245 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2246 while (op == self || op == args || op == res || op == t ||
2247 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2248 op = op->_ob_next;
2249 if (op == &refchain)
2250 return res;
2251 }
2252 if (PyList_Append(res, op) < 0) {
2253 Py_DECREF(res);
2254 return NULL;
2255 }
2256 op = op->_ob_next;
2257 }
2258 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002259}
2260
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002261#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002262
2263
2264/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00002265PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00002266
2267
2268/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002269Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002270
2271
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00002272/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00002273
Thomas Wouters334fb892000-07-25 12:56:38 +00002274void *
Fred Drake100814d2000-07-09 15:48:49 +00002275PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002276{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002277 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002278}
2279
Thomas Wouters334fb892000-07-25 12:56:38 +00002280void *
2281PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002282{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002283 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002284}
2285
2286void
Thomas Wouters334fb892000-07-25 12:56:38 +00002287PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002288{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002289 PyMem_FREE(p);
Guido van Rossumb18618d2000-05-03 23:44:39 +00002290}
2291
2292
Guido van Rossum86610361998-04-10 22:32:46 +00002293/* These methods are used to control infinite recursion in repr, str, print,
2294 etc. Container objects that may recursively contain themselves,
2295 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2296 Py_ReprLeave() to avoid infinite recursion.
2297
2298 Py_ReprEnter() returns 0 the first time it is called for a particular
2299 object and 1 every time thereafter. It returns -1 if an exception
2300 occurred. Py_ReprLeave() has no return value.
2301
2302 See dictobject.c and listobject.c for examples of use.
2303*/
2304
2305#define KEY "Py_Repr"
2306
2307int
Fred Drake100814d2000-07-09 15:48:49 +00002308Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002309{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002310 PyObject *dict;
2311 PyObject *list;
2312 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002313
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002314 dict = PyThreadState_GetDict();
2315 if (dict == NULL)
2316 return 0;
2317 list = PyDict_GetItemString(dict, KEY);
2318 if (list == NULL) {
2319 list = PyList_New(0);
2320 if (list == NULL)
2321 return -1;
2322 if (PyDict_SetItemString(dict, KEY, list) < 0)
2323 return -1;
2324 Py_DECREF(list);
2325 }
2326 i = PyList_GET_SIZE(list);
2327 while (--i >= 0) {
2328 if (PyList_GET_ITEM(list, i) == obj)
2329 return 1;
2330 }
2331 PyList_Append(list, obj);
2332 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002333}
2334
2335void
Fred Drake100814d2000-07-09 15:48:49 +00002336Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002337{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002338 PyObject *dict;
2339 PyObject *list;
2340 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002341
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002342 dict = PyThreadState_GetDict();
2343 if (dict == NULL)
2344 return;
2345 list = PyDict_GetItemString(dict, KEY);
2346 if (list == NULL || !PyList_Check(list))
2347 return;
2348 i = PyList_GET_SIZE(list);
2349 /* Count backwards because we always expect obj to be list[-1] */
2350 while (--i >= 0) {
2351 if (PyList_GET_ITEM(list, i) == obj) {
2352 PyList_SetSlice(list, i, i + 1, NULL);
2353 break;
2354 }
2355 }
Guido van Rossum86610361998-04-10 22:32:46 +00002356}
Guido van Rossumd724b232000-03-13 16:01:29 +00002357
Tim Peters803526b2002-07-07 05:13:56 +00002358/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002359
Tim Peters803526b2002-07-07 05:13:56 +00002360/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002361int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002362
Tim Peters803526b2002-07-07 05:13:56 +00002363/* List of objects that still need to be cleaned up, singly linked via their
2364 * gc headers' gc_prev pointers.
2365 */
2366PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002367
Tim Peters803526b2002-07-07 05:13:56 +00002368/* Add op to the _PyTrash_delete_later list. Called when the current
2369 * call-stack depth gets large. op must be a currently untracked gc'ed
2370 * object, with refcount 0. Py_DECREF must already have been called on it.
2371 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002372void
Fred Drake100814d2000-07-09 15:48:49 +00002373_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002374{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002375 assert(PyObject_IS_GC(op));
2376 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2377 assert(op->ob_refcnt == 0);
2378 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2379 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002380}
2381
Tim Peters803526b2002-07-07 05:13:56 +00002382/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2383 * the call-stack unwinds again.
2384 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002385void
Fred Drake100814d2000-07-09 15:48:49 +00002386_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002387{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002388 while (_PyTrash_delete_later) {
2389 PyObject *op = _PyTrash_delete_later;
2390 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002391
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002392 _PyTrash_delete_later =
2393 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002394
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002395 /* Call the deallocator directly. This used to try to
2396 * fool Py_DECREF into calling it indirectly, but
2397 * Py_DECREF was already called on this object, and in
2398 * assorted non-release builds calling Py_DECREF again ends
2399 * up distorting allocation statistics.
2400 */
2401 assert(op->ob_refcnt == 0);
2402 ++_PyTrash_delete_nesting;
2403 (*dealloc)(op);
2404 --_PyTrash_delete_nesting;
2405 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002406}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002407
2408#ifdef __cplusplus
2409}
2410#endif