blob: 65366b0b351b4c049690f507a353711f44cdecf5 [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 Peterson01c6e6f2009-04-18 22:15:26 +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 Pitrouc83ea132010-05-09 14:46:46 +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 Pitrouc83ea132010-05-09 14:46:46 +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 Pitrouc83ea132010-05-09 14:46:46 +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 Pitrouc83ea132010-05-09 14:46:46 +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. */
Martin v. Löwisb90304a2009-01-07 18:40:40 +000085static int unlist_types_without_objects;
86extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
87extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
88extern Py_ssize_t 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 Pitrouc83ea132010-05-09 14:46:46 +000092 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000093
Antoine Pitrouc83ea132010-05-09 14:46:46 +000094 for (tp = type_list; tp; tp = tp->tp_next)
95 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
96 "freed: %" PY_FORMAT_SIZE_T "d, "
97 "max in use: %" PY_FORMAT_SIZE_T "d\n",
98 tp->tp_name, tp->tp_allocs, tp->tp_frees,
99 tp->tp_maxalloc);
100 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
101 "empty: %" PY_FORMAT_SIZE_T "d\n",
102 fast_tuple_allocs, tuple_zero_allocs);
103 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
104 "neg: %" PY_FORMAT_SIZE_T "d\n",
105 quick_int_allocs, quick_neg_int_allocs);
106 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
107 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
108 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000109}
110
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000111PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000112get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000113{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000114 PyTypeObject *tp;
115 PyObject *result;
116 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000117
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 result = PyList_New(0);
119 if (result == NULL)
120 return NULL;
121 for (tp = type_list; tp; tp = tp->tp_next) {
122 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
123 tp->tp_frees, tp->tp_maxalloc);
124 if (v == NULL) {
125 Py_DECREF(result);
126 return NULL;
127 }
128 if (PyList_Append(result, v) < 0) {
129 Py_DECREF(v);
130 Py_DECREF(result);
131 return NULL;
132 }
133 Py_DECREF(v);
134 }
135 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000136}
137
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000138void
Fred Drake100814d2000-07-09 15:48:49 +0000139inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000140{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
142 /* first time; insert in linked list */
143 if (tp->tp_next != NULL) /* sanity check */
144 Py_FatalError("XXX inc_count sanity check");
145 if (type_list)
146 type_list->tp_prev = tp;
147 tp->tp_next = type_list;
148 /* Note that as of Python 2.2, heap-allocated type objects
149 * can go away, but this code requires that they stay alive
150 * until program exit. That's why we're careful with
151 * refcounts here. type_list gets a new reference to tp,
152 * while ownership of the reference type_list used to hold
153 * (if any) was transferred to tp->tp_next in the line above.
154 * tp is thus effectively immortal after this.
155 */
156 Py_INCREF(tp);
157 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000158#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000159 /* Also insert in the doubly-linked list of all objects,
160 * if not already there.
161 */
162 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000163#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000164 }
165 tp->tp_allocs++;
166 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
167 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000168}
Martin v. Löwis45294a92006-04-18 06:24:08 +0000169
170void dec_count(PyTypeObject *tp)
171{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 tp->tp_frees++;
173 if (unlist_types_without_objects &&
174 tp->tp_allocs == tp->tp_frees) {
175 /* unlink the type from type_list */
176 if (tp->tp_prev)
177 tp->tp_prev->tp_next = tp->tp_next;
178 else
179 type_list = tp->tp_next;
180 if (tp->tp_next)
181 tp->tp_next->tp_prev = tp->tp_prev;
182 tp->tp_next = tp->tp_prev = NULL;
183 Py_DECREF(tp);
184 }
Martin v. Löwis45294a92006-04-18 06:24:08 +0000185}
186
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000187#endif
188
Tim Peters7c321a82002-07-09 02:57:01 +0000189#ifdef Py_REF_DEBUG
190/* Log a fatal error; doesn't return. */
191void
192_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
193{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000194 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000195
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000196 PyOS_snprintf(buf, sizeof(buf),
197 "%s:%i object at %p has negative ref count "
198 "%" PY_FORMAT_SIZE_T "d",
199 fname, lineno, op, op->ob_refcnt);
200 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000201}
202
203#endif /* Py_REF_DEBUG */
204
Thomas Heller1328b522004-04-22 17:23:49 +0000205void
206Py_IncRef(PyObject *o)
207{
208 Py_XINCREF(o);
209}
210
211void
212Py_DecRef(PyObject *o)
213{
214 Py_XDECREF(o);
215}
216
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000217PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000218PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000220 if (op == NULL)
221 return PyErr_NoMemory();
222 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
223 Py_TYPE(op) = tp;
224 _Py_NewReference(op);
225 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226}
227
Guido van Rossumb18618d2000-05-03 23:44:39 +0000228PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000229PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000231 if (op == NULL)
232 return (PyVarObject *) PyErr_NoMemory();
233 /* Any changes should be reflected in PyObject_INIT_VAR */
234 op->ob_size = size;
235 Py_TYPE(op) = tp;
236 _Py_NewReference((PyObject *)op);
237 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000238}
239
240PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000241_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000242{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000243 PyObject *op;
244 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
245 if (op == NULL)
246 return PyErr_NoMemory();
247 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000248}
249
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000250PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000251_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000253 PyVarObject *op;
254 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
255 op = (PyVarObject *) PyObject_MALLOC(size);
256 if (op == NULL)
257 return (PyVarObject *)PyErr_NoMemory();
258 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000259}
260
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000261/* for binary compatibility with 2.2 */
262#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000263void
Fred Drake100814d2000-07-09 15:48:49 +0000264_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000265{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000266 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267}
268
Neal Norwitz1a997502003-01-13 20:13:12 +0000269/* Implementation of PyObject_Print with recursion checking */
270static int
271internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000273 int ret = 0;
274 if (nesting > 10) {
275 PyErr_SetString(PyExc_RuntimeError, "print recursion");
276 return -1;
277 }
278 if (PyErr_CheckSignals())
279 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000280#ifdef USE_STACKCHECK
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000281 if (PyOS_CheckStack()) {
282 PyErr_SetString(PyExc_MemoryError, "stack overflow");
283 return -1;
284 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000285#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000286 clearerr(fp); /* Clear any previous error condition */
287 if (op == NULL) {
288 Py_BEGIN_ALLOW_THREADS
289 fprintf(fp, "<nil>");
290 Py_END_ALLOW_THREADS
291 }
292 else {
293 if (op->ob_refcnt <= 0)
294 /* XXX(twouters) cast refcount to long until %zd is
295 universally available */
296 Py_BEGIN_ALLOW_THREADS
297 fprintf(fp, "<refcnt %ld at %p>",
298 (long)op->ob_refcnt, op);
299 Py_END_ALLOW_THREADS
300 else if (Py_TYPE(op)->tp_print == NULL) {
301 PyObject *s;
302 if (flags & Py_PRINT_RAW)
303 s = PyObject_Str(op);
304 else
305 s = PyObject_Repr(op);
306 if (s == NULL)
307 ret = -1;
308 else {
309 ret = internal_print(s, fp, Py_PRINT_RAW,
310 nesting+1);
311 }
312 Py_XDECREF(s);
313 }
314 else
315 ret = (*Py_TYPE(op)->tp_print)(op, fp, flags);
316 }
317 if (ret == 0) {
318 if (ferror(fp)) {
319 PyErr_SetFromErrno(PyExc_IOError);
320 clearerr(fp);
321 ret = -1;
322 }
323 }
324 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325}
326
Neal Norwitz1a997502003-01-13 20:13:12 +0000327int
328PyObject_Print(PyObject *op, FILE *fp, int flags)
329{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 return internal_print(op, fp, flags, 0);
Neal Norwitz1a997502003-01-13 20:13:12 +0000331}
332
333
Barry Warsaw9bf16442001-01-23 16:24:35 +0000334/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000335void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000337 if (op == NULL)
338 fprintf(stderr, "NULL\n");
339 else {
Georg Brandld3eaa742009-04-05 11:07:14 +0000340#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000341 PyGILState_STATE gil;
Georg Brandld3eaa742009-04-05 11:07:14 +0000342#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000343 fprintf(stderr, "object : ");
Georg Brandld3eaa742009-04-05 11:07:14 +0000344#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000345 gil = PyGILState_Ensure();
Georg Brandld3eaa742009-04-05 11:07:14 +0000346#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000347 (void)PyObject_Print(op, stderr, 0);
Georg Brandld3eaa742009-04-05 11:07:14 +0000348#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000349 PyGILState_Release(gil);
Georg Brandld3eaa742009-04-05 11:07:14 +0000350#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000351 /* XXX(twouters) cast refcount to long until %zd is
352 universally available */
353 fprintf(stderr, "\n"
354 "type : %s\n"
355 "refcount: %ld\n"
356 "address : %p\n",
357 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
358 (long)op->ob_refcnt,
359 op);
360 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000361}
Barry Warsaw903138f2001-01-23 16:33:18 +0000362
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000364PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000366 if (PyErr_CheckSignals())
367 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000368#ifdef USE_STACKCHECK
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000369 if (PyOS_CheckStack()) {
370 PyErr_SetString(PyExc_MemoryError, "stack overflow");
371 return NULL;
372 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000373#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000374 if (v == NULL)
375 return PyString_FromString("<NULL>");
376 else if (Py_TYPE(v)->tp_repr == NULL)
377 return PyString_FromFormat("<%s object at %p>",
378 Py_TYPE(v)->tp_name, v);
379 else {
380 PyObject *res;
Serhiy Storchakab7a2c172018-02-02 16:29:02 +0200381 /* It is possible for a type to have a tp_repr representation that
382 loops infinitely. */
383 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
384 return NULL;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000385 res = (*Py_TYPE(v)->tp_repr)(v);
Serhiy Storchakab7a2c172018-02-02 16:29:02 +0200386 Py_LeaveRecursiveCall();
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000387 if (res == NULL)
388 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000389#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000390 if (PyUnicode_Check(res)) {
391 PyObject* str;
392 str = PyUnicode_AsEncodedString(res, NULL, NULL);
393 Py_DECREF(res);
394 if (str)
395 res = str;
396 else
397 return NULL;
398 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000399#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000400 if (!PyString_Check(res)) {
401 PyErr_Format(PyExc_TypeError,
402 "__repr__ returned non-string (type %.200s)",
403 Py_TYPE(res)->tp_name);
404 Py_DECREF(res);
405 return NULL;
406 }
407 return res;
408 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409}
410
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000412_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000413{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000414 PyObject *res;
415 int type_ok;
416 if (v == NULL)
417 return PyString_FromString("<NULL>");
418 if (PyString_CheckExact(v)) {
419 Py_INCREF(v);
420 return v;
421 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000422#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000423 if (PyUnicode_CheckExact(v)) {
424 Py_INCREF(v);
425 return v;
426 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000427#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000428 if (Py_TYPE(v)->tp_str == NULL)
429 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000430
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000431 /* It is possible for a type to have a tp_str representation that loops
432 infinitely. */
433 if (Py_EnterRecursiveCall(" while getting the str of an object"))
434 return NULL;
435 res = (*Py_TYPE(v)->tp_str)(v);
436 Py_LeaveRecursiveCall();
437 if (res == NULL)
438 return NULL;
439 type_ok = PyString_Check(res);
Neil Schemenauercf52c072005-08-12 17:34:58 +0000440#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 type_ok = type_ok || PyUnicode_Check(res);
Neil Schemenauercf52c072005-08-12 17:34:58 +0000442#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000443 if (!type_ok) {
444 PyErr_Format(PyExc_TypeError,
445 "__str__ returned non-string (type %.200s)",
446 Py_TYPE(res)->tp_name);
447 Py_DECREF(res);
448 return NULL;
449 }
450 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000451}
452
453PyObject *
454PyObject_Str(PyObject *v)
455{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000456 PyObject *res = _PyObject_Str(v);
457 if (res == NULL)
458 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000459#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000460 if (PyUnicode_Check(res)) {
461 PyObject* str;
462 str = PyUnicode_AsEncodedString(res, NULL, NULL);
463 Py_DECREF(res);
464 if (str)
465 res = str;
466 else
467 return NULL;
468 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000469#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000470 assert(PyString_Check(res));
471 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000472}
473
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000474#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000475PyObject *
476PyObject_Unicode(PyObject *v)
477{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000478 PyObject *res;
479 PyObject *func;
480 PyObject *str;
481 int unicode_method_found = 0;
Benjamin Peterson6b3f8d32013-01-02 09:36:23 -0600482 static PyObject *unicodestr = NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000483
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000484 if (v == NULL) {
485 res = PyString_FromString("<NULL>");
486 if (res == NULL)
487 return NULL;
488 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
489 Py_DECREF(res);
490 return str;
491 } else if (PyUnicode_CheckExact(v)) {
492 Py_INCREF(v);
493 return v;
494 }
Nick Coghlan524b7772008-07-08 14:08:04 +0000495
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000496 if (PyInstance_Check(v)) {
497 /* We're an instance of a classic class */
498 /* Try __unicode__ from the instance -- alas we have no type */
Benjamin Peterson6b3f8d32013-01-02 09:36:23 -0600499 if (!unicodestr) {
500 unicodestr = PyString_InternFromString("__unicode__");
501 if (!unicodestr)
502 return NULL;
503 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000504 func = PyObject_GetAttr(v, unicodestr);
505 if (func != NULL) {
506 unicode_method_found = 1;
507 res = PyObject_CallFunctionObjArgs(func, NULL);
508 Py_DECREF(func);
509 }
510 else {
511 PyErr_Clear();
512 }
513 }
514 else {
515 /* Not a classic class instance, try __unicode__. */
516 func = _PyObject_LookupSpecial(v, "__unicode__", &unicodestr);
517 if (func != NULL) {
518 unicode_method_found = 1;
519 res = PyObject_CallFunctionObjArgs(func, NULL);
520 Py_DECREF(func);
521 }
522 else if (PyErr_Occurred())
523 return NULL;
524 }
Nick Coghlan524b7772008-07-08 14:08:04 +0000525
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000526 /* Didn't find __unicode__ */
527 if (!unicode_method_found) {
528 if (PyUnicode_Check(v)) {
529 /* For a Unicode subtype that's didn't overwrite __unicode__,
530 return a true Unicode object with the same data. */
531 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
532 PyUnicode_GET_SIZE(v));
533 }
534 if (PyString_CheckExact(v)) {
535 Py_INCREF(v);
536 res = v;
537 }
538 else {
539 if (Py_TYPE(v)->tp_str != NULL)
540 res = (*Py_TYPE(v)->tp_str)(v);
541 else
542 res = PyObject_Repr(v);
543 }
544 }
Nick Coghlan524b7772008-07-08 14:08:04 +0000545
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 if (res == NULL)
547 return NULL;
548 if (!PyUnicode_Check(res)) {
549 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
550 Py_DECREF(res);
551 res = str;
552 }
553 return res;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000554}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000555#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000556
557
Guido van Rossuma4073002002-05-31 20:03:54 +0000558/* Helper to warn about deprecated tp_compare return values. Return:
559 -2 for an exception;
560 -1 if v < w;
561 0 if v == w;
562 1 if v > w.
563 (This function cannot return 2.)
564*/
565static int
566adjust_tp_compare(int c)
567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 if (PyErr_Occurred()) {
569 if (c != -1 && c != -2) {
570 PyObject *t, *v, *tb;
571 PyErr_Fetch(&t, &v, &tb);
572 if (PyErr_Warn(PyExc_RuntimeWarning,
573 "tp_compare didn't return -1 or -2 "
574 "for exception") < 0) {
575 Py_XDECREF(t);
576 Py_XDECREF(v);
577 Py_XDECREF(tb);
578 }
579 else
580 PyErr_Restore(t, v, tb);
581 }
582 return -2;
583 }
584 else if (c < -1 || c > 1) {
585 if (PyErr_Warn(PyExc_RuntimeWarning,
586 "tp_compare didn't return -1, 0 or 1") < 0)
587 return -2;
588 else
589 return c < -1 ? -1 : 1;
590 }
591 else {
592 assert(c >= -1 && c <= 1);
593 return c;
594 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000595}
596
597
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000598/* Macro to get the tp_richcompare field of a type if defined */
599#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000600 ? (t)->tp_richcompare : NULL)
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000601
Guido van Rossume797ec12001-01-17 15:24:28 +0000602/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000603int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000604
Guido van Rossume797ec12001-01-17 15:24:28 +0000605/* Try a genuine rich comparison, returning an object. Return:
606 NULL for exception;
607 NotImplemented if this particular rich comparison is not implemented or
608 undefined;
609 some object not equal to NotImplemented if it is implemented
610 (this latter object may not be a Boolean).
611*/
612static PyObject *
613try_rich_compare(PyObject *v, PyObject *w, int op)
614{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000615 richcmpfunc f;
616 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000617
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 if (v->ob_type != w->ob_type &&
619 PyType_IsSubtype(w->ob_type, v->ob_type) &&
620 (f = RICHCOMPARE(w->ob_type)) != NULL) {
621 res = (*f)(w, v, _Py_SwappedOp[op]);
622 if (res != Py_NotImplemented)
623 return res;
624 Py_DECREF(res);
625 }
626 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
627 res = (*f)(v, w, op);
628 if (res != Py_NotImplemented)
629 return res;
630 Py_DECREF(res);
631 }
632 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
633 return (*f)(w, v, _Py_SwappedOp[op]);
634 }
635 res = Py_NotImplemented;
636 Py_INCREF(res);
637 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000638}
639
640/* Try a genuine rich comparison, returning an int. Return:
641 -1 for exception (including the case where try_rich_compare() returns an
642 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000643 0 if the outcome is false;
644 1 if the outcome is true;
645 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000646*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000647static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000648try_rich_compare_bool(PyObject *v, PyObject *w, int op)
649{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000650 PyObject *res;
651 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000652
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000653 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
654 return 2; /* Shortcut, avoid INCREF+DECREF */
655 res = try_rich_compare(v, w, op);
656 if (res == NULL)
657 return -1;
658 if (res == Py_NotImplemented) {
659 Py_DECREF(res);
660 return 2;
661 }
662 ok = PyObject_IsTrue(res);
663 Py_DECREF(res);
664 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000665}
666
667/* Try rich comparisons to determine a 3-way comparison. Return:
668 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000669 -1 if v < w;
670 0 if v == w;
671 1 if v > w;
672 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000673*/
674static int
675try_rich_to_3way_compare(PyObject *v, PyObject *w)
676{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000677 static struct { int op; int outcome; } tries[3] = {
678 /* Try this operator, and if it is true, use this outcome: */
679 {Py_EQ, 0},
680 {Py_LT, -1},
681 {Py_GT, 1},
682 };
683 int i;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000684
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000685 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
686 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000687
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000688 for (i = 0; i < 3; i++) {
689 switch (try_rich_compare_bool(v, w, tries[i].op)) {
690 case -1:
691 return -2;
692 case 1:
693 return tries[i].outcome;
694 }
695 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000696
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000697 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000698}
699
700/* Try a 3-way comparison, returning an int. Return:
701 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000702 -1 if v < w;
703 0 if v == w;
704 1 if v > w;
705 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000706*/
707static int
708try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 int c;
711 cmpfunc f;
Guido van Rossume797ec12001-01-17 15:24:28 +0000712
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000713 /* Comparisons involving instances are given to instance_compare,
714 which has the same return conventions as this function. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000715
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000716 f = v->ob_type->tp_compare;
717 if (PyInstance_Check(v))
718 return (*f)(v, w);
719 if (PyInstance_Check(w))
720 return (*w->ob_type->tp_compare)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000721
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000722 /* If both have the same (non-NULL) tp_compare, use it. */
723 if (f != NULL && f == w->ob_type->tp_compare) {
724 c = (*f)(v, w);
725 return adjust_tp_compare(c);
726 }
Guido van Rossumab3b0342001-09-18 20:38:53 +0000727
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000728 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
729 if (f == _PyObject_SlotCompare ||
730 w->ob_type->tp_compare == _PyObject_SlotCompare)
731 return _PyObject_SlotCompare(v, w);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000732
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 /* If we're here, v and w,
734 a) are not instances;
735 b) have different types or a type without tp_compare; and
736 c) don't have a user-defined tp_compare.
737 tp_compare implementations in C assume that both arguments
738 have their type, so we give up if the coercion fails or if
739 it yields types which are still incompatible (which can
740 happen with a user-defined nb_coerce).
741 */
742 c = PyNumber_CoerceEx(&v, &w);
743 if (c < 0)
744 return -2;
745 if (c > 0)
746 return 2;
747 f = v->ob_type->tp_compare;
748 if (f != NULL && f == w->ob_type->tp_compare) {
749 c = (*f)(v, w);
750 Py_DECREF(v);
751 Py_DECREF(w);
752 return adjust_tp_compare(c);
753 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000754
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000755 /* No comparison defined */
756 Py_DECREF(v);
757 Py_DECREF(w);
758 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000759}
760
Guido van Rossume797ec12001-01-17 15:24:28 +0000761/* Final fallback 3-way comparison, returning an int. Return:
762 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000763 -1 if v < w;
764 0 if v == w;
765 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000766*/
767static int
768default_3way_compare(PyObject *v, PyObject *w)
769{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000770 int c;
771 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000772
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000773 if (v->ob_type == w->ob_type) {
774 /* When comparing these pointers, they must be cast to
775 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
776 * uintptr_t). ANSI specifies that pointer compares other
777 * than == and != to non-related structures are undefined.
778 */
779 Py_uintptr_t vv = (Py_uintptr_t)v;
780 Py_uintptr_t ww = (Py_uintptr_t)w;
781 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
782 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000783
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000784 /* None is smaller than anything */
785 if (v == Py_None)
786 return -1;
787 if (w == Py_None)
788 return 1;
Guido van Rossum0871e932001-01-22 19:28:09 +0000789
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 /* different type: compare type names; numbers are smaller */
791 if (PyNumber_Check(v))
792 vname = "";
793 else
794 vname = v->ob_type->tp_name;
795 if (PyNumber_Check(w))
796 wname = "";
797 else
798 wname = w->ob_type->tp_name;
799 c = strcmp(vname, wname);
800 if (c < 0)
801 return -1;
802 if (c > 0)
803 return 1;
804 /* Same type name, or (more likely) incomparable numeric types */
805 return ((Py_uintptr_t)(v->ob_type) < (
806 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000807}
808
Tim Peters6d60b2e2001-05-07 20:53:51 +0000809/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000810 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000811 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000812 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000813 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000814 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000815 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000816*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000817static int
Fred Drake100814d2000-07-09 15:48:49 +0000818do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000819{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000820 int c;
821 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000822
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 if (v->ob_type == w->ob_type
824 && (f = v->ob_type->tp_compare) != NULL) {
825 c = (*f)(v, w);
826 if (PyInstance_Check(v)) {
827 /* Instance tp_compare has a different signature.
828 But if it returns undefined we fall through. */
829 if (c != 2)
830 return c;
831 /* Else fall through to try_rich_to_3way_compare() */
832 }
833 else
834 return adjust_tp_compare(c);
835 }
836 /* We only get here if one of the following is true:
837 a) v and w have different types
838 b) v and w have the same type, which doesn't have tp_compare
839 c) v and w are instances, and either __cmp__ is not defined or
840 __cmp__ returns NotImplemented
841 */
842 c = try_rich_to_3way_compare(v, w);
843 if (c < 2)
844 return c;
845 c = try_3way_compare(v, w);
846 if (c < 2)
847 return c;
848 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000849}
850
Tim Petersc99213f2001-11-04 05:57:16 +0000851/* Compare v to w. Return
852 -1 if v < w or exception (PyErr_Occurred() true in latter case).
853 0 if v == w.
854 1 if v > w.
855 XXX The docs (C API manual) say the return value is undefined in case
856 XXX of error.
857*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000858int
Fred Drake100814d2000-07-09 15:48:49 +0000859PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000860{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000861 int result;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000862
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000863 if (v == NULL || w == NULL) {
864 PyErr_BadInternalCall();
865 return -1;
866 }
867 if (v == w)
868 return 0;
869 if (Py_EnterRecursiveCall(" in cmp"))
870 return -1;
871 result = do_cmp(v, w);
872 Py_LeaveRecursiveCall();
873 return result < 0 ? -1 : result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000874}
875
Tim Petersc99213f2001-11-04 05:57:16 +0000876/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000877static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000878convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000879{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000880 PyObject *result;
881 switch (op) {
882 case Py_LT: c = c < 0; break;
883 case Py_LE: c = c <= 0; break;
884 case Py_EQ: c = c == 0; break;
885 case Py_NE: c = c != 0; break;
886 case Py_GT: c = c > 0; break;
887 case Py_GE: c = c >= 0; break;
888 }
889 result = c ? Py_True : Py_False;
890 Py_INCREF(result);
891 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000892}
Tim Peters803526b2002-07-07 05:13:56 +0000893
Tim Petersc99213f2001-11-04 05:57:16 +0000894/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
895 Return
896 NULL if error
897 Py_True if v op w
898 Py_False if not (v op w)
899*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000900static PyObject *
901try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
902{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000903 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000904
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000905 c = try_3way_compare(v, w);
906 if (c >= 2) {
Steven Bethardae42f332008-03-18 17:26:10 +0000907
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000908 /* Py3K warning if types are not equal and comparison isn't == or != */
909 if (Py_Py3kWarningFlag &&
910 v->ob_type != w->ob_type && op != Py_EQ && op != Py_NE &&
911 PyErr_WarnEx(PyExc_DeprecationWarning,
912 "comparing unequal types not supported "
913 "in 3.x", 1) < 0) {
914 return NULL;
915 }
Steven Bethardae42f332008-03-18 17:26:10 +0000916
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000917 c = default_3way_compare(v, w);
918 }
919 if (c <= -2)
920 return NULL;
921 return convert_3way_to_object(op, c);
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000922}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000923
Tim Petersc99213f2001-11-04 05:57:16 +0000924/* Do rich comparison on v and w. Return
925 NULL if error
926 Else a new reference to an object other than Py_NotImplemented, usually(?):
927 Py_True if v op w
928 Py_False if not (v op w)
929*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000930static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000931do_richcmp(PyObject *v, PyObject *w, int op)
932{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000933 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000934
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000935 res = try_rich_compare(v, w, op);
936 if (res != Py_NotImplemented)
937 return res;
938 Py_DECREF(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000939
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000940 return try_3way_to_rich_compare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000941}
942
Tim Petersc99213f2001-11-04 05:57:16 +0000943/* Return:
944 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000945 some object not equal to NotImplemented if it is implemented
946 (this latter object may not be a Boolean).
947*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000948PyObject *
949PyObject_RichCompare(PyObject *v, PyObject *w, int op)
950{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000951 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000952
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 assert(Py_LT <= op && op <= Py_GE);
954 if (Py_EnterRecursiveCall(" in cmp"))
955 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000956
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000957 /* If the types are equal, and not old-style instances, try to
958 get out cheap (don't bother with coercions etc.). */
959 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
960 cmpfunc fcmp;
961 richcmpfunc frich = RICHCOMPARE(v->ob_type);
962 /* If the type has richcmp, try it first. try_rich_compare
963 tries it two-sided, which is not needed since we've a
964 single type only. */
965 if (frich != NULL) {
966 res = (*frich)(v, w, op);
967 if (res != Py_NotImplemented)
968 goto Done;
969 Py_DECREF(res);
970 }
971 /* No richcmp, or this particular richmp not implemented.
972 Try 3-way cmp. */
973 fcmp = v->ob_type->tp_compare;
974 if (fcmp != NULL) {
975 int c = (*fcmp)(v, w);
976 c = adjust_tp_compare(c);
977 if (c == -2) {
978 res = NULL;
979 goto Done;
980 }
981 res = convert_3way_to_object(op, c);
982 goto Done;
983 }
984 }
Tim Peters67754e92001-11-04 07:29:31 +0000985
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000986 /* Fast path not taken, or couldn't deliver a useful result. */
987 res = do_richcmp(v, w, op);
Tim Peters67754e92001-11-04 07:29:31 +0000988Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000989 Py_LeaveRecursiveCall();
990 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000991}
992
Tim Petersde9725f2001-05-05 10:06:17 +0000993/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000994int
995PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
996{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 PyObject *res;
998 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000999
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001000 /* Quick result when objects are the same.
1001 Guarantees that identity implies equality. */
1002 if (v == w) {
1003 if (op == Py_EQ)
1004 return 1;
1005 else if (op == Py_NE)
1006 return 0;
1007 }
Raymond Hettinger93d44812004-03-21 17:01:44 +00001008
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001009 res = PyObject_RichCompare(v, w, op);
1010 if (res == NULL)
1011 return -1;
1012 if (PyBool_Check(res))
1013 ok = (res == Py_True);
1014 else
1015 ok = PyObject_IsTrue(res);
1016 Py_DECREF(res);
1017 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +00001018}
Fred Drake13634cf2000-06-29 19:17:04 +00001019
1020/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001021 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +00001022
1023 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1024*/
1025
1026long
Fred Drake100814d2000-07-09 15:48:49 +00001027_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001028{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 double intpart, fractpart;
1030 int expo;
1031 long hipart;
1032 long x; /* the final hash value */
1033 /* This is designed so that Python numbers of different types
1034 * that compare equal hash to the same value; otherwise comparisons
1035 * of mapping keys will turn out weird.
1036 */
Tim Peters39dce292000-08-15 03:34:48 +00001037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 if (!Py_IS_FINITE(v)) {
1039 if (Py_IS_INFINITY(v))
1040 return v < 0 ? -271828 : 314159;
1041 else
1042 return 0;
1043 }
1044 fractpart = modf(v, &intpart);
1045 if (fractpart == 0.0) {
1046 /* This must return the same hash as an equal int or long. */
1047 if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) {
1048 /* Convert to long and use its hash. */
1049 PyObject *plong; /* converted to Python long */
1050 plong = PyLong_FromDouble(v);
1051 if (plong == NULL)
1052 return -1;
1053 x = PyObject_Hash(plong);
1054 Py_DECREF(plong);
1055 return x;
1056 }
1057 /* Fits in a C long == a Python int, so is its own hash. */
1058 x = (long)intpart;
1059 if (x == -1)
1060 x = -2;
1061 return x;
1062 }
1063 /* The fractional part is non-zero, so we don't have to worry about
1064 * making this match the hash of some other type.
1065 * Use frexp to get at the bits in the double.
1066 * Since the VAX D double format has 56 mantissa bits, which is the
1067 * most of any double format in use, each of these parts may have as
1068 * many as (but no more than) 56 significant bits.
1069 * So, assuming sizeof(long) >= 4, each part can be broken into two
1070 * longs; frexp and multiplication are used to do that.
1071 * Also, since the Cray double format has 15 exponent bits, which is
1072 * the most of any double format in use, shifting the exponent field
1073 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
1074 */
1075 v = frexp(v, &expo);
1076 v *= 2147483648.0; /* 2**31 */
1077 hipart = (long)v; /* take the top 32 bits */
1078 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1079 x = hipart + (long)v + (expo << 15);
1080 if (x == -1)
1081 x = -2;
1082 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001083}
1084
1085long
Fred Drake100814d2000-07-09 15:48:49 +00001086_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001087{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001088 long x;
1089 size_t y = (size_t)p;
1090 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
1091 excessive hash collisions for dicts and sets */
1092 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
1093 x = (long)y;
1094 if (x == -1)
1095 x = -2;
1096 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001097}
1098
Nick Coghlan53663a62008-07-15 14:27:37 +00001099long
1100PyObject_HashNotImplemented(PyObject *self)
1101{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001102 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1103 self->ob_type->tp_name);
1104 return -1;
Nick Coghlan53663a62008-07-15 14:27:37 +00001105}
Fred Drake13634cf2000-06-29 19:17:04 +00001106
Barry Warsaw1e13eb02012-02-20 20:42:21 -05001107_Py_HashSecret_t _Py_HashSecret;
1108
Guido van Rossum9bfef441993-03-29 10:43:31 +00001109long
Fred Drake100814d2000-07-09 15:48:49 +00001110PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001111{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001112 PyTypeObject *tp = v->ob_type;
1113 if (tp->tp_hash != NULL)
1114 return (*tp->tp_hash)(v);
1115 /* To keep to the general practice that inheriting
1116 * solely from object in C code should work without
1117 * an explicit call to PyType_Ready, we implicitly call
1118 * PyType_Ready here and then check the tp_hash slot again
1119 */
1120 if (tp->tp_dict == NULL) {
1121 if (PyType_Ready(tp) < 0)
1122 return -1;
1123 if (tp->tp_hash != NULL)
1124 return (*tp->tp_hash)(v);
1125 }
1126 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
1127 return _Py_HashPointer(v); /* Use address as hash value */
1128 }
1129 /* If there's a cmp but no hash defined, the object can't be hashed */
1130 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001131}
1132
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001133PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001134PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001135{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001136 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001138 if (Py_TYPE(v)->tp_getattr != NULL)
1139 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1140 w = PyString_InternFromString(name);
1141 if (w == NULL)
1142 return NULL;
1143 res = PyObject_GetAttr(v, w);
1144 Py_XDECREF(w);
1145 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001146}
1147
1148int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001149PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001150{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 PyObject *res = PyObject_GetAttrString(v, name);
1152 if (res != NULL) {
1153 Py_DECREF(res);
1154 return 1;
1155 }
1156 PyErr_Clear();
1157 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001158}
1159
1160int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001161PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001162{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001163 PyObject *s;
1164 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001165
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001166 if (Py_TYPE(v)->tp_setattr != NULL)
1167 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1168 s = PyString_InternFromString(name);
1169 if (s == NULL)
1170 return -1;
1171 res = PyObject_SetAttr(v, s, w);
1172 Py_XDECREF(s);
1173 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001174}
1175
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001176PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001177PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001178{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001181 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001182#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001183 /* The Unicode to string conversion is done here because the
1184 existing tp_getattro slots expect a string object as name
1185 and we wouldn't want to break those. */
1186 if (PyUnicode_Check(name)) {
1187 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1188 if (name == NULL)
1189 return NULL;
1190 }
1191 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001192#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001193 {
1194 PyErr_Format(PyExc_TypeError,
1195 "attribute name must be string, not '%.200s'",
1196 Py_TYPE(name)->tp_name);
1197 return NULL;
1198 }
1199 }
1200 if (tp->tp_getattro != NULL)
1201 return (*tp->tp_getattro)(v, name);
1202 if (tp->tp_getattr != NULL)
1203 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1204 PyErr_Format(PyExc_AttributeError,
1205 "'%.50s' object has no attribute '%.400s'",
1206 tp->tp_name, PyString_AS_STRING(name));
1207 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001208}
1209
1210int
Fred Drake100814d2000-07-09 15:48:49 +00001211PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001212{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001213 PyObject *res = PyObject_GetAttr(v, name);
1214 if (res != NULL) {
1215 Py_DECREF(res);
1216 return 1;
1217 }
1218 PyErr_Clear();
1219 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001220}
1221
1222int
Fred Drake100814d2000-07-09 15:48:49 +00001223PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001224{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001225 PyTypeObject *tp = Py_TYPE(v);
1226 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001227
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001228 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001229#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001230 /* The Unicode to string conversion is done here because the
1231 existing tp_setattro slots expect a string object as name
1232 and we wouldn't want to break those. */
1233 if (PyUnicode_Check(name)) {
1234 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1235 if (name == NULL)
1236 return -1;
1237 }
1238 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001239#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001240 {
1241 PyErr_Format(PyExc_TypeError,
1242 "attribute name must be string, not '%.200s'",
1243 Py_TYPE(name)->tp_name);
1244 return -1;
1245 }
1246 }
1247 else
1248 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001250 PyString_InternInPlace(&name);
1251 if (tp->tp_setattro != NULL) {
1252 err = (*tp->tp_setattro)(v, name, value);
1253 Py_DECREF(name);
1254 return err;
1255 }
1256 if (tp->tp_setattr != NULL) {
1257 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1258 Py_DECREF(name);
1259 return err;
1260 }
1261 Py_DECREF(name);
1262 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1263 PyErr_Format(PyExc_TypeError,
1264 "'%.100s' object has no attributes "
1265 "(%s .%.100s)",
1266 tp->tp_name,
1267 value==NULL ? "del" : "assign to",
1268 PyString_AS_STRING(name));
1269 else
1270 PyErr_Format(PyExc_TypeError,
1271 "'%.100s' object has only read-only attributes "
1272 "(%s .%.100s)",
1273 tp->tp_name,
1274 value==NULL ? "del" : "assign to",
1275 PyString_AS_STRING(name));
1276 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277}
1278
1279/* Helper to get a pointer to an object's __dict__ slot, if any */
1280
1281PyObject **
1282_PyObject_GetDictPtr(PyObject *obj)
1283{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001284 Py_ssize_t dictoffset;
1285 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001287 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1288 return NULL;
1289 dictoffset = tp->tp_dictoffset;
1290 if (dictoffset == 0)
1291 return NULL;
1292 if (dictoffset < 0) {
1293 Py_ssize_t tsize;
1294 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001295
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001296 tsize = ((PyVarObject *)obj)->ob_size;
1297 if (tsize < 0)
1298 tsize = -tsize;
1299 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001300
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001301 dictoffset += (long)size;
1302 assert(dictoffset > 0);
1303 assert(dictoffset % SIZEOF_VOID_P == 0);
1304 }
1305 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306}
1307
Tim Peters6d6c1a32001-08-02 04:15:00 +00001308PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001309PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001310{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001311 Py_INCREF(obj);
1312 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001313}
1314
Amaury Forgeot d'Arca40d5732009-01-12 23:36:55 +00001315/* Helper used when the __next__ method is removed from a type:
1316 tp_iternext is never NULL and can be safely called without checking
1317 on every iteration.
1318 */
1319
1320PyObject *
1321_PyObject_NextNotImplemented(PyObject *self)
1322{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001323 PyErr_Format(PyExc_TypeError,
1324 "'%.200s' object is not iterable",
1325 Py_TYPE(self)->tp_name);
1326 return NULL;
Amaury Forgeot d'Arca40d5732009-01-12 23:36:55 +00001327}
1328
Michael W. Hudson1593f502004-09-14 17:09:47 +00001329/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1330
Raymond Hettinger01538262003-03-17 08:24:35 +00001331PyObject *
Antoine Pitroua4083502010-08-28 18:29:13 +00001332_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001334 PyTypeObject *tp = Py_TYPE(obj);
1335 PyObject *descr = NULL;
1336 PyObject *res = NULL;
1337 descrgetfunc f;
1338 Py_ssize_t dictoffset;
1339 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001341 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001342#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 /* The Unicode to string conversion is done here because the
1344 existing tp_setattro slots expect a string object as name
1345 and we wouldn't want to break those. */
1346 if (PyUnicode_Check(name)) {
1347 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1348 if (name == NULL)
1349 return NULL;
1350 }
1351 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001352#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001353 {
1354 PyErr_Format(PyExc_TypeError,
1355 "attribute name must be string, not '%.200s'",
1356 Py_TYPE(name)->tp_name);
1357 return NULL;
1358 }
1359 }
1360 else
1361 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001363 if (tp->tp_dict == NULL) {
1364 if (PyType_Ready(tp) < 0)
1365 goto done;
1366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001368#if 0 /* XXX this is not quite _PyType_Lookup anymore */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001369 /* Inline _PyType_Lookup */
1370 {
1371 Py_ssize_t i, n;
1372 PyObject *mro, *base, *dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001373
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001374 /* Look in tp_dict of types in MRO */
1375 mro = tp->tp_mro;
1376 assert(mro != NULL);
1377 assert(PyTuple_Check(mro));
1378 n = PyTuple_GET_SIZE(mro);
1379 for (i = 0; i < n; i++) {
1380 base = PyTuple_GET_ITEM(mro, i);
1381 if (PyClass_Check(base))
1382 dict = ((PyClassObject *)base)->cl_dict;
1383 else {
1384 assert(PyType_Check(base));
1385 dict = ((PyTypeObject *)base)->tp_dict;
1386 }
1387 assert(dict && PyDict_Check(dict));
1388 descr = PyDict_GetItem(dict, name);
1389 if (descr != NULL)
1390 break;
1391 }
1392 }
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001393#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001394 descr = _PyType_Lookup(tp, name);
Amaury Forgeot d'Arce4c270c2008-01-14 00:29:41 +00001395#endif
Guido van Rossum056fbf42002-08-19 19:22:50 +00001396
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001397 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001399 f = NULL;
1400 if (descr != NULL &&
1401 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1402 f = descr->ob_type->tp_descr_get;
1403 if (f != NULL && PyDescr_IsData(descr)) {
1404 res = f(descr, obj, (PyObject *)obj->ob_type);
1405 Py_DECREF(descr);
1406 goto done;
1407 }
1408 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409
Antoine Pitroua4083502010-08-28 18:29:13 +00001410 if (dict == NULL) {
1411 /* Inline _PyObject_GetDictPtr */
1412 dictoffset = tp->tp_dictoffset;
1413 if (dictoffset != 0) {
1414 if (dictoffset < 0) {
1415 Py_ssize_t tsize;
1416 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001417
Antoine Pitroua4083502010-08-28 18:29:13 +00001418 tsize = ((PyVarObject *)obj)->ob_size;
1419 if (tsize < 0)
1420 tsize = -tsize;
1421 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001422
Antoine Pitroua4083502010-08-28 18:29:13 +00001423 dictoffset += (long)size;
1424 assert(dictoffset > 0);
1425 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001426 }
Antoine Pitroua4083502010-08-28 18:29:13 +00001427 dictptr = (PyObject **) ((char *)obj + dictoffset);
1428 dict = *dictptr;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001429 }
1430 }
Antoine Pitroua4083502010-08-28 18:29:13 +00001431 if (dict != NULL) {
1432 Py_INCREF(dict);
1433 res = PyDict_GetItem(dict, name);
1434 if (res != NULL) {
1435 Py_INCREF(res);
1436 Py_XDECREF(descr);
1437 Py_DECREF(dict);
1438 goto done;
1439 }
1440 Py_DECREF(dict);
1441 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001443 if (f != NULL) {
1444 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1445 Py_DECREF(descr);
1446 goto done;
1447 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001449 if (descr != NULL) {
1450 res = descr;
1451 /* descr was already increfed above */
1452 goto done;
1453 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001455 PyErr_Format(PyExc_AttributeError,
1456 "'%.50s' object has no attribute '%.400s'",
1457 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001458 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001459 Py_DECREF(name);
1460 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001461}
1462
Antoine Pitroua4083502010-08-28 18:29:13 +00001463PyObject *
1464PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1465{
1466 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1467}
1468
Tim Peters6d6c1a32001-08-02 04:15:00 +00001469int
Antoine Pitroua4083502010-08-28 18:29:13 +00001470_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1471 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001473 PyTypeObject *tp = Py_TYPE(obj);
1474 PyObject *descr;
1475 descrsetfunc f;
1476 PyObject **dictptr;
1477 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001480#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001481 /* The Unicode to string conversion is done here because the
1482 existing tp_setattro slots expect a string object as name
1483 and we wouldn't want to break those. */
1484 if (PyUnicode_Check(name)) {
1485 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1486 if (name == NULL)
1487 return -1;
1488 }
1489 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001490#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 {
1492 PyErr_Format(PyExc_TypeError,
1493 "attribute name must be string, not '%.200s'",
1494 Py_TYPE(name)->tp_name);
1495 return -1;
1496 }
1497 }
1498 else
1499 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001501 if (tp->tp_dict == NULL) {
1502 if (PyType_Ready(tp) < 0)
1503 goto done;
1504 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 descr = _PyType_Lookup(tp, name);
1507 f = NULL;
1508 if (descr != NULL &&
1509 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1510 f = descr->ob_type->tp_descr_set;
1511 if (f != NULL && PyDescr_IsData(descr)) {
1512 res = f(descr, obj, value);
1513 goto done;
1514 }
1515 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001516
Antoine Pitroua4083502010-08-28 18:29:13 +00001517 if (dict == NULL) {
1518 dictptr = _PyObject_GetDictPtr(obj);
1519 if (dictptr != NULL) {
1520 dict = *dictptr;
1521 if (dict == NULL && value != NULL) {
1522 dict = PyDict_New();
1523 if (dict == NULL)
1524 goto done;
1525 *dictptr = dict;
1526 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001527 }
Antoine Pitroua4083502010-08-28 18:29:13 +00001528 }
1529 if (dict != NULL) {
1530 Py_INCREF(dict);
1531 if (value == NULL)
1532 res = PyDict_DelItem(dict, name);
1533 else
1534 res = PyDict_SetItem(dict, name, value);
1535 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1536 PyErr_SetObject(PyExc_AttributeError, name);
1537 Py_DECREF(dict);
1538 goto done;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001539 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001541 if (f != NULL) {
1542 res = f(descr, obj, value);
1543 goto done;
1544 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001545
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001546 if (descr == NULL) {
1547 PyErr_Format(PyExc_AttributeError,
1548 "'%.100s' object has no attribute '%.200s'",
1549 tp->tp_name, PyString_AS_STRING(name));
1550 goto done;
1551 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001552
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001553 PyErr_Format(PyExc_AttributeError,
1554 "'%.50s' object attribute '%.400s' is read-only",
1555 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001556 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001557 Py_DECREF(name);
1558 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001559}
1560
Antoine Pitroua4083502010-08-28 18:29:13 +00001561int
1562PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1563{
1564 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1565}
1566
1567
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001568/* Test a value used as condition, e.g., in a for or if statement.
1569 Return -1 if an error occurred */
1570
1571int
Fred Drake100814d2000-07-09 15:48:49 +00001572PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001573{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001574 Py_ssize_t res;
1575 if (v == Py_True)
1576 return 1;
1577 if (v == Py_False)
1578 return 0;
1579 if (v == Py_None)
1580 return 0;
1581 else if (v->ob_type->tp_as_number != NULL &&
1582 v->ob_type->tp_as_number->nb_nonzero != NULL)
1583 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
1584 else if (v->ob_type->tp_as_mapping != NULL &&
1585 v->ob_type->tp_as_mapping->mp_length != NULL)
1586 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1587 else if (v->ob_type->tp_as_sequence != NULL &&
1588 v->ob_type->tp_as_sequence->sq_length != NULL)
1589 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1590 else
1591 return 1;
1592 /* if it is negative, it should be either -1 or -2 */
1593 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001594}
1595
Tim Peters803526b2002-07-07 05:13:56 +00001596/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001597 Return -1 if an error occurred */
1598
1599int
Fred Drake100814d2000-07-09 15:48:49 +00001600PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001601{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001602 int res;
1603 res = PyObject_IsTrue(v);
1604 if (res < 0)
1605 return res;
1606 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001607}
1608
Guido van Rossum5524a591995-01-10 15:26:20 +00001609/* Coerce two numeric types to the "larger" one.
1610 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001611 Return value:
1612 -1 if an error occurred;
1613 0 if the coercion succeeded (and then the reference counts are increased);
1614 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001615*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001616int
Fred Drake100814d2000-07-09 15:48:49 +00001617PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001618{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001619 register PyObject *v = *pv;
1620 register PyObject *w = *pw;
1621 int res;
Guido van Rossum5524a591995-01-10 15:26:20 +00001622
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001623 /* Shortcut only for old-style types */
1624 if (v->ob_type == w->ob_type &&
1625 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1626 {
1627 Py_INCREF(v);
1628 Py_INCREF(w);
1629 return 0;
1630 }
1631 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1632 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1633 if (res <= 0)
1634 return res;
1635 }
1636 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1637 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1638 if (res <= 0)
1639 return res;
1640 }
1641 return 1;
Guido van Rossum242c6421997-11-19 16:03:17 +00001642}
1643
Guido van Rossume797ec12001-01-17 15:24:28 +00001644/* Coerce two numeric types to the "larger" one.
1645 Increment the reference count on each argument.
1646 Return -1 and raise an exception if no coercion is possible
1647 (and then no reference count is incremented).
1648*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001649int
Fred Drake100814d2000-07-09 15:48:49 +00001650PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001651{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001652 int err = PyNumber_CoerceEx(pv, pw);
1653 if (err <= 0)
1654 return err;
1655 PyErr_SetString(PyExc_TypeError, "number coercion failed");
1656 return -1;
Guido van Rossum5524a591995-01-10 15:26:20 +00001657}
1658
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001659
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001660/* Test whether an object can be called */
1661
1662int
Fred Drake100814d2000-07-09 15:48:49 +00001663PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001664{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001665 if (x == NULL)
1666 return 0;
1667 if (PyInstance_Check(x)) {
1668 PyObject *call = PyObject_GetAttrString(x, "__call__");
1669 if (call == NULL) {
1670 PyErr_Clear();
1671 return 0;
1672 }
1673 /* Could test recursively but don't, for fear of endless
1674 recursion if some joker sets self.__call__ = self */
1675 Py_DECREF(call);
1676 return 1;
1677 }
1678 else {
1679 return x->ob_type->tp_call != NULL;
1680 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001681}
1682
Georg Brandl871f1bc2007-03-12 13:17:36 +00001683/* ------------------------- PyObject_Dir() helpers ------------------------- */
1684
Tim Peters7eea37e2001-09-04 22:08:56 +00001685/* Helper for PyObject_Dir.
1686 Merge the __dict__ of aclass into dict, and recursively also all
1687 the __dict__s of aclass's base classes. The order of merging isn't
1688 defined, as it's expected that only the final set of dict keys is
1689 interesting.
1690 Return 0 on success, -1 on error.
1691*/
1692
1693static int
1694merge_class_dict(PyObject* dict, PyObject* aclass)
1695{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001696 PyObject *classdict;
1697 PyObject *bases;
Tim Peters7eea37e2001-09-04 22:08:56 +00001698
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001699 assert(PyDict_Check(dict));
1700 assert(aclass);
Tim Peters7eea37e2001-09-04 22:08:56 +00001701
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001702 /* Merge in the type's dict (if any). */
1703 classdict = PyObject_GetAttrString(aclass, "__dict__");
1704 if (classdict == NULL)
1705 PyErr_Clear();
1706 else {
1707 int status = PyDict_Update(dict, classdict);
1708 Py_DECREF(classdict);
1709 if (status < 0)
1710 return -1;
1711 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001712
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001713 /* Recursively merge in the base types' (if any) dicts. */
1714 bases = PyObject_GetAttrString(aclass, "__bases__");
1715 if (bases == NULL)
1716 PyErr_Clear();
1717 else {
1718 /* We have no guarantee that bases is a real tuple */
1719 Py_ssize_t i, n;
1720 n = PySequence_Size(bases); /* This better be right */
1721 if (n < 0)
1722 PyErr_Clear();
1723 else {
1724 for (i = 0; i < n; i++) {
1725 int status;
1726 PyObject *base = PySequence_GetItem(bases, i);
1727 if (base == NULL) {
1728 Py_DECREF(bases);
1729 return -1;
1730 }
1731 status = merge_class_dict(dict, base);
1732 Py_DECREF(base);
1733 if (status < 0) {
1734 Py_DECREF(bases);
1735 return -1;
1736 }
1737 }
1738 }
1739 Py_DECREF(bases);
1740 }
1741 return 0;
Tim Peters7eea37e2001-09-04 22:08:56 +00001742}
1743
Tim Peters305b5852001-09-17 02:38:46 +00001744/* Helper for PyObject_Dir.
1745 If obj has an attr named attrname that's a list, merge its string
1746 elements into keys of dict.
1747 Return 0 on success, -1 on error. Errors due to not finding the attr,
1748 or the attr not being a list, are suppressed.
1749*/
1750
1751static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001752merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001753{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001754 PyObject *list;
1755 int result = 0;
Tim Peters305b5852001-09-17 02:38:46 +00001756
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001757 assert(PyDict_Check(dict));
1758 assert(obj);
1759 assert(attrname);
Tim Peters305b5852001-09-17 02:38:46 +00001760
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001761 list = PyObject_GetAttrString(obj, attrname);
1762 if (list == NULL)
1763 PyErr_Clear();
Tim Peters305b5852001-09-17 02:38:46 +00001764
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001765 else if (PyList_Check(list)) {
1766 int i;
1767 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1768 PyObject *item = PyList_GET_ITEM(list, i);
1769 if (PyString_Check(item)) {
1770 result = PyDict_SetItem(dict, item, Py_None);
1771 if (result < 0)
1772 break;
1773 }
1774 }
1775 if (Py_Py3kWarningFlag &&
1776 (strcmp(attrname, "__members__") == 0 ||
1777 strcmp(attrname, "__methods__") == 0)) {
1778 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1779 "__members__ and __methods__ not "
1780 "supported in 3.x", 1) < 0) {
1781 Py_XDECREF(list);
1782 return -1;
1783 }
1784 }
1785 }
Tim Peters305b5852001-09-17 02:38:46 +00001786
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001787 Py_XDECREF(list);
1788 return result;
Tim Peters305b5852001-09-17 02:38:46 +00001789}
1790
Georg Brandl871f1bc2007-03-12 13:17:36 +00001791/* Helper for PyObject_Dir without arguments: returns the local scope. */
1792static PyObject *
Jeremy Hylton26ca9252007-03-16 14:49:11 +00001793_dir_locals(void)
Tim Peters7eea37e2001-09-04 22:08:56 +00001794{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001795 PyObject *names;
1796 PyObject *locals = PyEval_GetLocals();
Tim Peters7eea37e2001-09-04 22:08:56 +00001797
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001798 if (locals == NULL) {
1799 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1800 return NULL;
1801 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001802
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001803 names = PyMapping_Keys(locals);
1804 if (!names)
1805 return NULL;
1806 if (!PyList_Check(names)) {
1807 PyErr_Format(PyExc_TypeError,
1808 "dir(): expected keys() of locals to be a list, "
1809 "not '%.200s'", Py_TYPE(names)->tp_name);
1810 Py_DECREF(names);
1811 return NULL;
1812 }
1813 /* the locals don't need to be DECREF'd */
1814 return names;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001815}
Tim Peters7eea37e2001-09-04 22:08:56 +00001816
Georg Brandl871f1bc2007-03-12 13:17:36 +00001817/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001818 We deliberately don't suck up its __class__, as methods belonging to the
1819 metaclass would probably be more confusing than helpful.
Georg Brandl871f1bc2007-03-12 13:17:36 +00001820*/
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001821static PyObject *
Georg Brandl871f1bc2007-03-12 13:17:36 +00001822_specialized_dir_type(PyObject *obj)
1823{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001824 PyObject *result = NULL;
1825 PyObject *dict = PyDict_New();
Georg Brandl871f1bc2007-03-12 13:17:36 +00001826
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001827 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1828 result = PyDict_Keys(dict);
Georg Brandl871f1bc2007-03-12 13:17:36 +00001829
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001830 Py_XDECREF(dict);
1831 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001832}
1833
1834/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1835static PyObject *
1836_specialized_dir_module(PyObject *obj)
1837{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001838 PyObject *result = NULL;
1839 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Georg Brandl871f1bc2007-03-12 13:17:36 +00001840
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001841 if (dict != NULL) {
1842 if (PyDict_Check(dict))
1843 result = PyDict_Keys(dict);
1844 else {
1845 char *name = PyModule_GetName(obj);
1846 if (name)
1847 PyErr_Format(PyExc_TypeError,
1848 "%.200s.__dict__ is not a dictionary",
1849 name);
1850 }
1851 }
Georg Brandl871f1bc2007-03-12 13:17:36 +00001852
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001853 Py_XDECREF(dict);
1854 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001855}
1856
1857/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1858 and recursively up the __class__.__bases__ chain.
1859*/
1860static PyObject *
1861_generic_dir(PyObject *obj)
1862{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001863 PyObject *result = NULL;
1864 PyObject *dict = NULL;
1865 PyObject *itsclass = NULL;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001866
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 /* Get __dict__ (which may or may not be a real dict...) */
1868 dict = PyObject_GetAttrString(obj, "__dict__");
1869 if (dict == NULL) {
1870 PyErr_Clear();
1871 dict = PyDict_New();
1872 }
1873 else if (!PyDict_Check(dict)) {
1874 Py_DECREF(dict);
1875 dict = PyDict_New();
1876 }
1877 else {
1878 /* Copy __dict__ to avoid mutating it. */
1879 PyObject *temp = PyDict_Copy(dict);
1880 Py_DECREF(dict);
1881 dict = temp;
1882 }
Georg Brandl871f1bc2007-03-12 13:17:36 +00001883
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001884 if (dict == NULL)
1885 goto error;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001886
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001887 /* Merge in __members__ and __methods__ (if any).
1888 * This is removed in Python 3000. */
1889 if (merge_list_attr(dict, obj, "__members__") < 0)
1890 goto error;
1891 if (merge_list_attr(dict, obj, "__methods__") < 0)
1892 goto error;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001893
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001894 /* Merge in attrs reachable from its class. */
1895 itsclass = PyObject_GetAttrString(obj, "__class__");
1896 if (itsclass == NULL)
1897 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1898 __class__ exists? */
1899 PyErr_Clear();
1900 else {
1901 if (merge_class_dict(dict, itsclass) != 0)
1902 goto error;
1903 }
1904
1905 result = PyDict_Keys(dict);
1906 /* fall through */
Georg Brandl871f1bc2007-03-12 13:17:36 +00001907error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001908 Py_XDECREF(itsclass);
1909 Py_XDECREF(dict);
1910 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001911}
1912
1913/* Helper for PyObject_Dir: object introspection.
1914 This calls one of the above specialized versions if no __dir__ method
1915 exists. */
1916static PyObject *
1917_dir_object(PyObject *obj)
1918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 PyObject *result = NULL;
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001920 static PyObject *dir_str = NULL;
Benjamin Petersonfd89af52011-05-23 17:11:21 -05001921 PyObject *dirfunc;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001922
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001923 assert(obj);
Benjamin Petersonfd89af52011-05-23 17:11:21 -05001924 if (PyInstance_Check(obj)) {
1925 dirfunc = PyObject_GetAttrString(obj, "__dir__");
Benjamin Peterson7f5cd452011-05-23 18:17:55 -05001926 if (dirfunc == NULL) {
1927 if (PyErr_ExceptionMatches(PyExc_AttributeError))
1928 PyErr_Clear();
1929 else
1930 return NULL;
1931 }
Benjamin Petersonfd89af52011-05-23 17:11:21 -05001932 }
1933 else {
1934 dirfunc = _PyObject_LookupSpecial(obj, "__dir__", &dir_str);
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001935 if (PyErr_Occurred())
1936 return NULL;
Benjamin Petersonfd89af52011-05-23 17:11:21 -05001937 }
1938 if (dirfunc == NULL) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001939 /* use default implementation */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001940 if (PyModule_Check(obj))
1941 result = _specialized_dir_module(obj);
1942 else if (PyType_Check(obj) || PyClass_Check(obj))
1943 result = _specialized_dir_type(obj);
1944 else
1945 result = _generic_dir(obj);
1946 }
1947 else {
1948 /* use __dir__ */
Benjamin Peterson8de87a62011-05-23 16:11:05 -05001949 result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001950 Py_DECREF(dirfunc);
1951 if (result == NULL)
1952 return NULL;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001953
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001954 /* result must be a list */
1955 /* XXX(gbrandl): could also check if all items are strings */
1956 if (!PyList_Check(result)) {
1957 PyErr_Format(PyExc_TypeError,
1958 "__dir__() must return a list, not %.200s",
1959 Py_TYPE(result)->tp_name);
1960 Py_DECREF(result);
1961 result = NULL;
1962 }
1963 }
Georg Brandl871f1bc2007-03-12 13:17:36 +00001964
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001965 return result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001966}
1967
1968/* Implementation of dir() -- if obj is NULL, returns the names in the current
1969 (local) scope. Otherwise, performs introspection of the object: returns a
1970 sorted list of attribute names (supposedly) accessible from the object
1971*/
1972PyObject *
1973PyObject_Dir(PyObject *obj)
1974{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001975 PyObject * result;
Georg Brandl871f1bc2007-03-12 13:17:36 +00001976
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001977 if (obj == NULL)
1978 /* no object -- introspect the locals */
1979 result = _dir_locals();
1980 else
1981 /* object -- introspect the object */
1982 result = _dir_object(obj);
Georg Brandl871f1bc2007-03-12 13:17:36 +00001983
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001984 assert(result == NULL || PyList_Check(result));
Georg Brandl871f1bc2007-03-12 13:17:36 +00001985
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001986 if (result != NULL && PyList_Sort(result) != 0) {
1987 /* sorting the list failed */
1988 Py_DECREF(result);
1989 result = NULL;
1990 }
1991
1992 return result;
Tim Peters7eea37e2001-09-04 22:08:56 +00001993}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001994
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001995/*
1996NoObject is usable as a non-NULL undefined value, used by the macro None.
1997There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001998so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001999(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002000*/
2001
Guido van Rossum0c182a11992-03-27 17:26:13 +00002002/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002004none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002005{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002006 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002007}
2008
Barry Warsaw9bf16442001-01-23 16:24:35 +00002009/* ARGUSED */
2010static void
Tim Peters803526b2002-07-07 05:13:56 +00002011none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00002012{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002013 /* This should never get called, but we also don't want to SEGV if
2014 * we accidentally decref None out of existence.
2015 */
2016 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00002017}
2018
2019
Alexandre Vassalottidf9460f2013-11-30 17:43:42 -08002020static PyTypeObject PyNone_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002021 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2022 "NoneType",
2023 0,
2024 0,
2025 none_dealloc, /*tp_dealloc*/ /*never called*/
2026 0, /*tp_print*/
2027 0, /*tp_getattr*/
2028 0, /*tp_setattr*/
2029 0, /*tp_compare*/
2030 none_repr, /*tp_repr*/
2031 0, /*tp_as_number*/
2032 0, /*tp_as_sequence*/
2033 0, /*tp_as_mapping*/
2034 (hashfunc)_Py_HashPointer, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002035};
2036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037PyObject _Py_NoneStruct = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002038 _PyObject_EXTRA_INIT
2039 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002040};
2041
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00002042/* NotImplemented is an object that can be used to signal that an
2043 operation is not implemented for the given type combination. */
2044
2045static PyObject *
2046NotImplemented_repr(PyObject *op)
2047{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002048 return PyString_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00002049}
2050
Alexandre Vassalottidf9460f2013-11-30 17:43:42 -08002051static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002052 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2053 "NotImplementedType",
2054 0,
2055 0,
2056 none_dealloc, /*tp_dealloc*/ /*never called*/
2057 0, /*tp_print*/
2058 0, /*tp_getattr*/
2059 0, /*tp_setattr*/
2060 0, /*tp_compare*/
2061 NotImplemented_repr, /*tp_repr*/
2062 0, /*tp_as_number*/
2063 0, /*tp_as_sequence*/
2064 0, /*tp_as_mapping*/
2065 0, /*tp_hash */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00002066};
2067
2068PyObject _Py_NotImplementedStruct = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002069 _PyObject_EXTRA_INIT
2070 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00002071};
2072
Guido van Rossumba21a492001-08-16 08:17:26 +00002073void
2074_Py_ReadyTypes(void)
2075{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002076 if (PyType_Ready(&PyType_Type) < 0)
2077 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002078
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002079 if (PyType_Ready(&_PyWeakref_RefType) < 0)
2080 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00002081
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002082 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
2083 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Peterson308c6ba2009-04-19 02:32:42 +00002084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002085 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
2086 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Peterson308c6ba2009-04-19 02:32:42 +00002087
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002088 if (PyType_Ready(&PyBool_Type) < 0)
2089 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00002090
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002091 if (PyType_Ready(&PyString_Type) < 0)
2092 Py_FatalError("Can't initialize str type");
Guido van Rossumcacfc072002-05-24 19:01:59 +00002093
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002094 if (PyType_Ready(&PyByteArray_Type) < 0)
2095 Py_FatalError("Can't initialize bytearray type");
Christian Heimes1a6387e2008-03-26 12:49:49 +00002096
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002097 if (PyType_Ready(&PyList_Type) < 0)
2098 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002099
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002100 if (PyType_Ready(&PyNone_Type) < 0)
2101 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002103 if (PyType_Ready(&PyNotImplemented_Type) < 0)
2104 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002105
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002106 if (PyType_Ready(&PyTraceBack_Type) < 0)
2107 Py_FatalError("Can't initialize traceback type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002108
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002109 if (PyType_Ready(&PySuper_Type) < 0)
2110 Py_FatalError("Can't initialize super type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002111
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002112 if (PyType_Ready(&PyBaseObject_Type) < 0)
2113 Py_FatalError("Can't initialize object type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002114
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002115 if (PyType_Ready(&PyRange_Type) < 0)
2116 Py_FatalError("Can't initialize xrange type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 if (PyType_Ready(&PyDict_Type) < 0)
2119 Py_FatalError("Can't initialize dict type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002120
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002121 if (PyType_Ready(&PySet_Type) < 0)
2122 Py_FatalError("Can't initialize set type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002123
Martin v. Löwised11a5d2012-05-20 10:42:17 +02002124#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002125 if (PyType_Ready(&PyUnicode_Type) < 0)
2126 Py_FatalError("Can't initialize unicode type");
Martin v. Löwised11a5d2012-05-20 10:42:17 +02002127#endif
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002129 if (PyType_Ready(&PySlice_Type) < 0)
2130 Py_FatalError("Can't initialize slice type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002131
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002132 if (PyType_Ready(&PyStaticMethod_Type) < 0)
2133 Py_FatalError("Can't initialize static method type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002134
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002135#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002136 if (PyType_Ready(&PyComplex_Type) < 0)
2137 Py_FatalError("Can't initialize complex type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002138#endif
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002139
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002140 if (PyType_Ready(&PyFloat_Type) < 0)
2141 Py_FatalError("Can't initialize float type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002142
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002143 if (PyType_Ready(&PyBuffer_Type) < 0)
2144 Py_FatalError("Can't initialize buffer type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002145
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002146 if (PyType_Ready(&PyLong_Type) < 0)
2147 Py_FatalError("Can't initialize long type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002148
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002149 if (PyType_Ready(&PyInt_Type) < 0)
2150 Py_FatalError("Can't initialize int type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002151
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002152 if (PyType_Ready(&PyFrozenSet_Type) < 0)
2153 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002155 if (PyType_Ready(&PyProperty_Type) < 0)
2156 Py_FatalError("Can't initialize property type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002157
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002158 if (PyType_Ready(&PyMemoryView_Type) < 0)
2159 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002160
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002161 if (PyType_Ready(&PyTuple_Type) < 0)
2162 Py_FatalError("Can't initialize tuple type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002163
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002164 if (PyType_Ready(&PyEnum_Type) < 0)
2165 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersond4d400c2009-04-18 20:12:47 +00002166
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002167 if (PyType_Ready(&PyReversed_Type) < 0)
2168 Py_FatalError("Can't initialize reversed type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002169
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002170 if (PyType_Ready(&PyCode_Type) < 0)
2171 Py_FatalError("Can't initialize code type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002172
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002173 if (PyType_Ready(&PyFrame_Type) < 0)
2174 Py_FatalError("Can't initialize frame type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002175
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002176 if (PyType_Ready(&PyCFunction_Type) < 0)
2177 Py_FatalError("Can't initialize builtin function type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002178
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002179 if (PyType_Ready(&PyMethod_Type) < 0)
2180 Py_FatalError("Can't initialize method type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002182 if (PyType_Ready(&PyFunction_Type) < 0)
2183 Py_FatalError("Can't initialize function type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002184
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002185 if (PyType_Ready(&PyClass_Type) < 0)
2186 Py_FatalError("Can't initialize class type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002187
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002188 if (PyType_Ready(&PyDictProxy_Type) < 0)
2189 Py_FatalError("Can't initialize dict proxy type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002190
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002191 if (PyType_Ready(&PyGen_Type) < 0)
2192 Py_FatalError("Can't initialize generator type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002193
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002194 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
2195 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002196
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002197 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
2198 Py_FatalError("Can't initialize wrapper type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002199
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002200 if (PyType_Ready(&PyInstance_Type) < 0)
2201 Py_FatalError("Can't initialize instance type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002202
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002203 if (PyType_Ready(&PyEllipsis_Type) < 0)
2204 Py_FatalError("Can't initialize ellipsis type");
Benjamin Peterson01c6e6f2009-04-18 22:15:26 +00002205
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002206 if (PyType_Ready(&PyMemberDescr_Type) < 0)
2207 Py_FatalError("Can't initialize member descriptor type");
Antoine Pitroud11f7fc2009-05-31 18:05:51 +00002208
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002209 if (PyType_Ready(&PyFile_Type) < 0)
2210 Py_FatalError("Can't initialize file type");
Benjamin Peterson6da3ed62012-10-30 23:21:10 -04002211
2212 if (PyType_Ready(&PyCapsule_Type) < 0)
2213 Py_FatalError("Can't initialize capsule type");
2214
2215 if (PyType_Ready(&PyCell_Type) < 0)
2216 Py_FatalError("Can't initialize cell type");
2217
2218 if (PyType_Ready(&PyCallIter_Type) < 0)
2219 Py_FatalError("Can't initialize call iter type");
2220
2221 if (PyType_Ready(&PySeqIter_Type) < 0)
2222 Py_FatalError("Can't initialize sequence iterator type");
Guido van Rossumba21a492001-08-16 08:17:26 +00002223}
2224
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002225
Guido van Rossum84a90321996-05-22 16:34:47 +00002226#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002227
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002228void
Fred Drake100814d2000-07-09 15:48:49 +00002229_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002230{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002231 _Py_INC_REFTOTAL;
2232 op->ob_refcnt = 1;
2233 _Py_AddToAllObjects(op, 1);
2234 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002235}
2236
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002237void
Fred Drake100814d2000-07-09 15:48:49 +00002238_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002239{
Guido van Rossumbffd6832000-01-20 22:32:56 +00002240#ifdef SLOW_UNREF_CHECK
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002241 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00002242#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002243 if (op->ob_refcnt < 0)
2244 Py_FatalError("UNREF negative refcnt");
2245 if (op == &refchain ||
2246 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
2247 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002248#ifdef SLOW_UNREF_CHECK
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002249 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
2250 if (p == op)
2251 break;
2252 }
2253 if (p == &refchain) /* Not found */
2254 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00002255#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002256 op->_ob_next->_ob_prev = op->_ob_prev;
2257 op->_ob_prev->_ob_next = op->_ob_next;
2258 op->_ob_next = op->_ob_prev = NULL;
2259 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002260}
2261
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002262void
Fred Drake100814d2000-07-09 15:48:49 +00002263_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002264{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002265 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2266 _Py_ForgetReference(op);
2267 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002268}
2269
Tim Peters269b2a62003-04-17 19:52:29 +00002270/* Print all live objects. Because PyObject_Print is called, the
2271 * interpreter must be in a healthy state.
2272 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002273void
Fred Drake100814d2000-07-09 15:48:49 +00002274_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002275{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002276 PyObject *op;
2277 fprintf(fp, "Remaining objects:\n");
2278 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
2279 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
2280 if (PyObject_Print(op, fp, 0) != 0)
2281 PyErr_Clear();
2282 putc('\n', fp);
2283 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002284}
2285
Tim Peters269b2a62003-04-17 19:52:29 +00002286/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
2287 * doesn't make any calls to the Python C API, so is always safe to call.
2288 */
2289void
2290_Py_PrintReferenceAddresses(FILE *fp)
2291{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002292 PyObject *op;
2293 fprintf(fp, "Remaining object addresses:\n");
2294 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
2295 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
2296 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00002297}
2298
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002299PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002300_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002301{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002302 int i, n;
2303 PyObject *t = NULL;
2304 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002305
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002306 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2307 return NULL;
2308 op = refchain._ob_next;
2309 res = PyList_New(0);
2310 if (res == NULL)
2311 return NULL;
2312 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2313 while (op == self || op == args || op == res || op == t ||
2314 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2315 op = op->_ob_next;
2316 if (op == &refchain)
2317 return res;
2318 }
2319 if (PyList_Append(res, op) < 0) {
2320 Py_DECREF(res);
2321 return NULL;
2322 }
2323 op = op->_ob_next;
2324 }
2325 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002326}
2327
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002328#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002329
2330
Larry Hastings402b73f2010-03-25 00:54:54 +00002331/* Hack to force loading of capsule.o */
2332PyTypeObject *_Py_capsule_hack = &PyCapsule_Type;
2333
2334
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002335/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00002336PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00002337
2338
2339/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002340Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002341
2342
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00002343/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00002344
Thomas Wouters334fb892000-07-25 12:56:38 +00002345void *
Fred Drake100814d2000-07-09 15:48:49 +00002346PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002347{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002348 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002349}
2350
Thomas Wouters334fb892000-07-25 12:56:38 +00002351void *
2352PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002353{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002354 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002355}
2356
2357void
Thomas Wouters334fb892000-07-25 12:56:38 +00002358PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002359{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002360 PyMem_FREE(p);
Guido van Rossumb18618d2000-05-03 23:44:39 +00002361}
2362
2363
Guido van Rossum86610361998-04-10 22:32:46 +00002364/* These methods are used to control infinite recursion in repr, str, print,
2365 etc. Container objects that may recursively contain themselves,
Martin Panterb44c4522016-05-29 08:13:58 +00002366 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00002367 Py_ReprLeave() to avoid infinite recursion.
2368
2369 Py_ReprEnter() returns 0 the first time it is called for a particular
2370 object and 1 every time thereafter. It returns -1 if an exception
2371 occurred. Py_ReprLeave() has no return value.
2372
2373 See dictobject.c and listobject.c for examples of use.
2374*/
2375
2376#define KEY "Py_Repr"
2377
2378int
Fred Drake100814d2000-07-09 15:48:49 +00002379Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002380{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002381 PyObject *dict;
2382 PyObject *list;
2383 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002384
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002385 dict = PyThreadState_GetDict();
2386 if (dict == NULL)
2387 return 0;
2388 list = PyDict_GetItemString(dict, KEY);
2389 if (list == NULL) {
2390 list = PyList_New(0);
2391 if (list == NULL)
2392 return -1;
2393 if (PyDict_SetItemString(dict, KEY, list) < 0)
2394 return -1;
2395 Py_DECREF(list);
2396 }
2397 i = PyList_GET_SIZE(list);
2398 while (--i >= 0) {
2399 if (PyList_GET_ITEM(list, i) == obj)
2400 return 1;
2401 }
2402 PyList_Append(list, obj);
2403 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002404}
2405
2406void
Fred Drake100814d2000-07-09 15:48:49 +00002407Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002408{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002409 PyObject *dict;
2410 PyObject *list;
2411 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002412
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002413 dict = PyThreadState_GetDict();
2414 if (dict == NULL)
2415 return;
2416 list = PyDict_GetItemString(dict, KEY);
2417 if (list == NULL || !PyList_Check(list))
2418 return;
2419 i = PyList_GET_SIZE(list);
2420 /* Count backwards because we always expect obj to be list[-1] */
2421 while (--i >= 0) {
2422 if (PyList_GET_ITEM(list, i) == obj) {
2423 PyList_SetSlice(list, i, i + 1, NULL);
2424 break;
2425 }
2426 }
Guido van Rossum86610361998-04-10 22:32:46 +00002427}
Guido van Rossumd724b232000-03-13 16:01:29 +00002428
Tim Peters803526b2002-07-07 05:13:56 +00002429/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002430
Tim Peters803526b2002-07-07 05:13:56 +00002431/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002432int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002433
Tim Peters803526b2002-07-07 05:13:56 +00002434/* List of objects that still need to be cleaned up, singly linked via their
2435 * gc headers' gc_prev pointers.
2436 */
2437PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002438
Tim Peters803526b2002-07-07 05:13:56 +00002439/* Add op to the _PyTrash_delete_later list. Called when the current
2440 * call-stack depth gets large. op must be a currently untracked gc'ed
2441 * object, with refcount 0. Py_DECREF must already have been called on it.
2442 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002443void
Fred Drake100814d2000-07-09 15:48:49 +00002444_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002445{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002446 assert(PyObject_IS_GC(op));
2447 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2448 assert(op->ob_refcnt == 0);
2449 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2450 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002451}
2452
Antoine Pitrou58098a72012-09-06 00:59:49 +02002453/* The equivalent API, using per-thread state recursion info */
2454void
2455_PyTrash_thread_deposit_object(PyObject *op)
2456{
2457 PyThreadState *tstate = PyThreadState_GET();
2458 assert(PyObject_IS_GC(op));
2459 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2460 assert(op->ob_refcnt == 0);
2461 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later;
2462 tstate->trash_delete_later = op;
2463}
2464
Tim Peters803526b2002-07-07 05:13:56 +00002465/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2466 * the call-stack unwinds again.
2467 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002468void
Fred Drake100814d2000-07-09 15:48:49 +00002469_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002470{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002471 while (_PyTrash_delete_later) {
2472 PyObject *op = _PyTrash_delete_later;
2473 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002474
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002475 _PyTrash_delete_later =
2476 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002477
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002478 /* Call the deallocator directly. This used to try to
2479 * fool Py_DECREF into calling it indirectly, but
2480 * Py_DECREF was already called on this object, and in
2481 * assorted non-release builds calling Py_DECREF again ends
2482 * up distorting allocation statistics.
2483 */
2484 assert(op->ob_refcnt == 0);
2485 ++_PyTrash_delete_nesting;
2486 (*dealloc)(op);
2487 --_PyTrash_delete_nesting;
2488 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002489}
Anthony Baxterac6bd462006-04-13 02:06:09 +00002490
Antoine Pitrou58098a72012-09-06 00:59:49 +02002491/* The equivalent API, using per-thread state recursion info */
2492void
2493_PyTrash_thread_destroy_chain(void)
2494{
2495 PyThreadState *tstate = PyThreadState_GET();
2496 while (tstate->trash_delete_later) {
2497 PyObject *op = tstate->trash_delete_later;
2498 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2499
2500 tstate->trash_delete_later =
2501 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2502
2503 /* Call the deallocator directly. This used to try to
2504 * fool Py_DECREF into calling it indirectly, but
2505 * Py_DECREF was already called on this object, and in
2506 * assorted non-release builds calling Py_DECREF again ends
2507 * up distorting allocation statistics.
2508 */
2509 assert(op->ob_refcnt == 0);
2510 ++tstate->trash_delete_nesting;
2511 (*dealloc)(op);
2512 --tstate->trash_delete_nesting;
2513 }
2514}
2515
Anthony Baxterac6bd462006-04-13 02:06:09 +00002516#ifdef __cplusplus
2517}
2518#endif