blob: db7882a620bc5aca6c3a0d4d8e03541581bf8e5d [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 Petersonfd838e62009-04-20 02:09:13 +00005#include "frameobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#ifdef __cplusplus
8extern "C" {
9#endif
10
Tim Peters34592512002-07-11 06:23:50 +000011#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000012Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013
14Py_ssize_t
15_Py_GetRefTotal(void)
16{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000029}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Guido van Rossum3f5da241990-12-20 15:06:42 +000032/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
33 These are used by the individual routines for object creation.
34 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000035
Tim Peters78be7992003-03-23 02:51:01 +000036#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000037/* Head of circular doubly-linked list of all objects. These are linked
38 * together via the _ob_prev and _ob_next members of a PyObject, which
39 * exist only in a Py_TRACE_REFS build.
40 */
Tim Peters78be7992003-03-23 02:51:01 +000041static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000042
Tim Peters7571a0f2003-03-23 17:52:28 +000043/* Insert op at the front of the list of all objects. If force is true,
44 * op is added even if _ob_prev and _ob_next are non-NULL already. If
45 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
46 * force should be true if and only if op points to freshly allocated,
47 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000048 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000049 * Note that objects are normally added to the list via _Py_NewReference,
50 * which is called by PyObject_Init. Not all objects are initialized that
51 * way, though; exceptions include statically allocated type objects, and
52 * statically allocated singletons (like Py_True and Py_None).
53 */
Tim Peters36eb4df2003-03-23 03:33:13 +000054void
Tim Peters7571a0f2003-03-23 17:52:28 +000055_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000056{
Tim Peters7571a0f2003-03-23 17:52:28 +000057#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (!force) {
59 /* If it's initialized memory, op must be in or out of
60 * the list unambiguously.
61 */
62 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
63 }
Tim Peters78be7992003-03-23 02:51:01 +000064#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (force || op->_ob_prev == NULL) {
66 op->_ob_next = refchain._ob_next;
67 op->_ob_prev = &refchain;
68 refchain._ob_next->_ob_prev = op;
69 refchain._ob_next = op;
70 }
Tim Peters7571a0f2003-03-23 17:52:28 +000071}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000073
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076/* All types are added to type_list, at least when
77 they get one object created. That makes them
78 immortal, which unfortunately contributes to
79 garbage itself. If unlist_types_without_objects
80 is set, they will be removed from the type_list
81 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000082static int unlist_types_without_objects;
83extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
84extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
85extern Py_ssize_t null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000086void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 for (tp = type_list; tp; tp = tp->tp_next)
92 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
93 "freed: %" PY_FORMAT_SIZE_T "d, "
94 "max in use: %" PY_FORMAT_SIZE_T "d\n",
95 tp->tp_name, tp->tp_allocs, tp->tp_frees,
96 tp->tp_maxalloc);
97 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
98 "empty: %" PY_FORMAT_SIZE_T "d\n",
99 fast_tuple_allocs, tuple_zero_allocs);
100 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
101 "neg: %" PY_FORMAT_SIZE_T "d\n",
102 quick_int_allocs, quick_neg_int_allocs);
103 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
104 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
105 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000106}
107
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000108PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000109get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyTypeObject *tp;
112 PyObject *result;
113 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 result = PyList_New(0);
116 if (result == NULL)
117 return NULL;
118 for (tp = type_list; tp; tp = tp->tp_next) {
119 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
120 tp->tp_frees, tp->tp_maxalloc);
121 if (v == NULL) {
122 Py_DECREF(result);
123 return NULL;
124 }
125 if (PyList_Append(result, v) < 0) {
126 Py_DECREF(v);
127 Py_DECREF(result);
128 return NULL;
129 }
130 Py_DECREF(v);
131 }
132 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000133}
134
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000135void
Fred Drake100814d2000-07-09 15:48:49 +0000136inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
139 /* first time; insert in linked list */
140 if (tp->tp_next != NULL) /* sanity check */
141 Py_FatalError("XXX inc_count sanity check");
142 if (type_list)
143 type_list->tp_prev = tp;
144 tp->tp_next = type_list;
145 /* Note that as of Python 2.2, heap-allocated type objects
146 * can go away, but this code requires that they stay alive
147 * until program exit. That's why we're careful with
148 * refcounts here. type_list gets a new reference to tp,
149 * while ownership of the reference type_list used to hold
150 * (if any) was transferred to tp->tp_next in the line above.
151 * tp is thus effectively immortal after this.
152 */
153 Py_INCREF(tp);
154 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000155#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 /* Also insert in the doubly-linked list of all objects,
157 * if not already there.
158 */
159 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000160#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 }
162 tp->tp_allocs++;
163 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
164 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000165}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166
167void dec_count(PyTypeObject *tp)
168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 tp->tp_frees++;
170 if (unlist_types_without_objects &&
171 tp->tp_allocs == tp->tp_frees) {
172 /* unlink the type from type_list */
173 if (tp->tp_prev)
174 tp->tp_prev->tp_next = tp->tp_next;
175 else
176 type_list = tp->tp_next;
177 if (tp->tp_next)
178 tp->tp_next->tp_prev = tp->tp_prev;
179 tp->tp_next = tp->tp_prev = NULL;
180 Py_DECREF(tp);
181 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000182}
183
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000184#endif
185
Tim Peters7c321a82002-07-09 02:57:01 +0000186#ifdef Py_REF_DEBUG
187/* Log a fatal error; doesn't return. */
188void
189_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyOS_snprintf(buf, sizeof(buf),
194 "%s:%i object at %p has negative ref count "
195 "%" PY_FORMAT_SIZE_T "d",
196 fname, lineno, op, op->ob_refcnt);
197 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000198}
199
200#endif /* Py_REF_DEBUG */
201
Thomas Heller1328b522004-04-22 17:23:49 +0000202void
203Py_IncRef(PyObject *o)
204{
205 Py_XINCREF(o);
206}
207
208void
209Py_DecRef(PyObject *o)
210{
211 Py_XDECREF(o);
212}
213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000215PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (op == NULL)
218 return PyErr_NoMemory();
219 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
220 Py_TYPE(op) = tp;
221 _Py_NewReference(op);
222 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223}
224
Guido van Rossumb18618d2000-05-03 23:44:39 +0000225PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000226PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (op == NULL)
229 return (PyVarObject *) PyErr_NoMemory();
230 /* Any changes should be reflected in PyObject_INIT_VAR */
231 op->ob_size = size;
232 Py_TYPE(op) = tp;
233 _Py_NewReference((PyObject *)op);
234 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000235}
236
237PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000238_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyObject *op;
241 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
242 if (op == NULL)
243 return PyErr_NoMemory();
244 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000245}
246
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000247PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000248_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 PyVarObject *op;
251 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
252 op = (PyVarObject *) PyObject_MALLOC(size);
253 if (op == NULL)
254 return (PyVarObject *)PyErr_NoMemory();
255 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000256}
257
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000258int
259PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 if (PyErr_CheckSignals())
263 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000264#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if (PyOS_CheckStack()) {
266 PyErr_SetString(PyExc_MemoryError, "stack overflow");
267 return -1;
268 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000269#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 clearerr(fp); /* Clear any previous error condition */
271 if (op == NULL) {
272 Py_BEGIN_ALLOW_THREADS
273 fprintf(fp, "<nil>");
274 Py_END_ALLOW_THREADS
275 }
276 else {
277 if (op->ob_refcnt <= 0)
278 /* XXX(twouters) cast refcount to long until %zd is
279 universally available */
280 Py_BEGIN_ALLOW_THREADS
281 fprintf(fp, "<refcnt %ld at %p>",
282 (long)op->ob_refcnt, op);
283 Py_END_ALLOW_THREADS
284 else {
285 PyObject *s;
286 if (flags & Py_PRINT_RAW)
287 s = PyObject_Str(op);
288 else
289 s = PyObject_Repr(op);
290 if (s == NULL)
291 ret = -1;
292 else if (PyBytes_Check(s)) {
293 fwrite(PyBytes_AS_STRING(s), 1,
294 PyBytes_GET_SIZE(s), fp);
295 }
296 else if (PyUnicode_Check(s)) {
297 PyObject *t;
Victor Stinner372ac5e2010-05-17 01:26:01 +0000298 t = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(s),
299 PyUnicode_GET_SIZE(s),
300 "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (t == NULL)
302 ret = 0;
303 else {
304 fwrite(PyBytes_AS_STRING(t), 1,
305 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000306 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 }
308 }
309 else {
310 PyErr_Format(PyExc_TypeError,
311 "str() or repr() returned '%.100s'",
312 s->ob_type->tp_name);
313 ret = -1;
314 }
315 Py_XDECREF(s);
316 }
317 }
318 if (ret == 0) {
319 if (ferror(fp)) {
320 PyErr_SetFromErrno(PyExc_IOError);
321 clearerr(fp);
322 ret = -1;
323 }
324 }
325 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326}
327
Guido van Rossum38938152006-08-21 23:36:26 +0000328/* For debugging convenience. Set a breakpoint here and call it from your DLL */
329void
Thomas Woutersb2137042007-02-01 18:02:27 +0000330_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000331{
332}
333
Neal Norwitz1a997502003-01-13 20:13:12 +0000334
Barry Warsaw9bf16442001-01-23 16:24:35 +0000335/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000336void
337_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (op == NULL)
340 fprintf(stderr, "NULL\n");
341 else {
Georg Brandldfd73442009-04-05 11:47:34 +0000342#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 PyGILState_STATE gil;
Georg Brandldfd73442009-04-05 11:47:34 +0000344#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 fprintf(stderr, "object : ");
Georg Brandldfd73442009-04-05 11:47:34 +0000346#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 gil = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000348#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 (void)PyObject_Print(op, stderr, 0);
Georg Brandldfd73442009-04-05 11:47:34 +0000350#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 PyGILState_Release(gil);
Georg Brandldfd73442009-04-05 11:47:34 +0000352#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 /* XXX(twouters) cast refcount to long until %zd is
354 universally available */
355 fprintf(stderr, "\n"
356 "type : %s\n"
357 "refcount: %ld\n"
358 "address : %p\n",
359 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
360 (long)op->ob_refcnt,
361 op);
362 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000363}
Barry Warsaw903138f2001-01-23 16:33:18 +0000364
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000366PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 PyObject *res;
369 if (PyErr_CheckSignals())
370 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000371#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (PyOS_CheckStack()) {
373 PyErr_SetString(PyExc_MemoryError, "stack overflow");
374 return NULL;
375 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000376#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 if (v == NULL)
378 return PyUnicode_FromString("<NULL>");
379 if (Py_TYPE(v)->tp_repr == NULL)
380 return PyUnicode_FromFormat("<%s object at %p>",
381 v->ob_type->tp_name, v);
382 res = (*v->ob_type->tp_repr)(v);
383 if (res != NULL && !PyUnicode_Check(res)) {
384 PyErr_Format(PyExc_TypeError,
385 "__repr__ returned non-string (type %.200s)",
386 res->ob_type->tp_name);
387 Py_DECREF(res);
388 return NULL;
389 }
390 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391}
392
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000394PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 PyObject *res;
397 if (PyErr_CheckSignals())
398 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000399#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (PyOS_CheckStack()) {
401 PyErr_SetString(PyExc_MemoryError, "stack overflow");
402 return NULL;
403 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000404#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (v == NULL)
406 return PyUnicode_FromString("<NULL>");
407 if (PyUnicode_CheckExact(v)) {
408 Py_INCREF(v);
409 return v;
410 }
411 if (Py_TYPE(v)->tp_str == NULL)
412 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 /* It is possible for a type to have a tp_str representation that loops
415 infinitely. */
416 if (Py_EnterRecursiveCall(" while getting the str of an object"))
417 return NULL;
418 res = (*Py_TYPE(v)->tp_str)(v);
419 Py_LeaveRecursiveCall();
420 if (res == NULL)
421 return NULL;
422 if (!PyUnicode_Check(res)) {
423 PyErr_Format(PyExc_TypeError,
424 "__str__ returned non-string (type %.200s)",
425 Py_TYPE(res)->tp_name);
426 Py_DECREF(res);
427 return NULL;
428 }
429 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000430}
431
Georg Brandl559e5d72008-06-11 18:37:52 +0000432PyObject *
433PyObject_ASCII(PyObject *v)
434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 repr = PyObject_Repr(v);
438 if (repr == NULL)
439 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
442 ascii = PyUnicode_EncodeASCII(
443 PyUnicode_AS_UNICODE(repr),
444 PyUnicode_GET_SIZE(repr),
445 "backslashreplace");
Georg Brandl559e5d72008-06-11 18:37:52 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 Py_DECREF(repr);
448 if (ascii == NULL)
449 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 res = PyUnicode_DecodeASCII(
452 PyBytes_AS_STRING(ascii),
453 PyBytes_GET_SIZE(ascii),
454 NULL);
455
456 Py_DECREF(ascii);
457 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000458}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000459
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000460PyObject *
461PyObject_Bytes(PyObject *v)
462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PyObject *result, *func;
464 static PyObject *bytesstring = NULL;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (v == NULL)
467 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (PyBytes_CheckExact(v)) {
470 Py_INCREF(v);
471 return v;
472 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring);
475 if (func != NULL) {
476 result = PyObject_CallFunctionObjArgs(func, NULL);
477 Py_DECREF(func);
478 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000479 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000481 PyErr_Format(PyExc_TypeError,
482 "__bytes__ returned non-bytes (type %.200s)",
483 Py_TYPE(result)->tp_name);
484 Py_DECREF(result);
485 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 }
487 return result;
488 }
489 else if (PyErr_Occurred())
490 return NULL;
491 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000492}
493
Mark Dickinsonc008a172009-02-01 13:59:22 +0000494/* For Python 3.0.1 and later, the old three-way comparison has been
495 completely removed in favour of rich comparisons. PyObject_Compare() and
496 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000497 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000498 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000499
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000500 See (*) below for practical amendments.
501
Mark Dickinsonc008a172009-02-01 13:59:22 +0000502 tp_richcompare gets called with a first argument of the appropriate type
503 and a second object of an arbitrary type. We never do any kind of
504 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000505
Mark Dickinsonc008a172009-02-01 13:59:22 +0000506 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000507
508 NULL if an exception occurred
509 NotImplemented if the requested comparison is not implemented
510 any other false value if the requested comparison is false
511 any other true value if the requested comparison is true
512
513 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
514 NotImplemented.
515
516 (*) Practical amendments:
517
518 - If rich comparison returns NotImplemented, == and != are decided by
519 comparing the object pointer (i.e. falling back to the base object
520 implementation).
521
Guido van Rossuma4073002002-05-31 20:03:54 +0000522*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000523
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000524/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000525int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000526
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000527static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000528
529/* Perform a rich comparison, raising TypeError when the requested comparison
530 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000531static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000532do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 richcmpfunc f;
535 PyObject *res;
536 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (v->ob_type != w->ob_type &&
539 PyType_IsSubtype(w->ob_type, v->ob_type) &&
540 (f = w->ob_type->tp_richcompare) != NULL) {
541 checked_reverse_op = 1;
542 res = (*f)(w, v, _Py_SwappedOp[op]);
543 if (res != Py_NotImplemented)
544 return res;
545 Py_DECREF(res);
546 }
547 if ((f = v->ob_type->tp_richcompare) != NULL) {
548 res = (*f)(v, w, op);
549 if (res != Py_NotImplemented)
550 return res;
551 Py_DECREF(res);
552 }
553 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
554 res = (*f)(w, v, _Py_SwappedOp[op]);
555 if (res != Py_NotImplemented)
556 return res;
557 Py_DECREF(res);
558 }
559 /* If neither object implements it, provide a sensible default
560 for == and !=, but raise an exception for ordering. */
561 switch (op) {
562 case Py_EQ:
563 res = (v == w) ? Py_True : Py_False;
564 break;
565 case Py_NE:
566 res = (v != w) ? Py_True : Py_False;
567 break;
568 default:
569 /* XXX Special-case None so it doesn't show as NoneType() */
570 PyErr_Format(PyExc_TypeError,
571 "unorderable types: %.100s() %s %.100s()",
572 v->ob_type->tp_name,
573 opstrings[op],
574 w->ob_type->tp_name);
575 return NULL;
576 }
577 Py_INCREF(res);
578 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000579}
580
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000581/* Perform a rich comparison with object result. This wraps do_richcompare()
582 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000583
Guido van Rossume797ec12001-01-17 15:24:28 +0000584PyObject *
585PyObject_RichCompare(PyObject *v, PyObject *w, int op)
586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 assert(Py_LT <= op && op <= Py_GE);
590 if (v == NULL || w == NULL) {
591 if (!PyErr_Occurred())
592 PyErr_BadInternalCall();
593 return NULL;
594 }
595 if (Py_EnterRecursiveCall(" in comparison"))
596 return NULL;
597 res = do_richcompare(v, w, op);
598 Py_LeaveRecursiveCall();
599 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000600}
601
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000602/* Perform a rich comparison with integer result. This wraps
603 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000604int
605PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyObject *res;
608 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* Quick result when objects are the same.
611 Guarantees that identity implies equality. */
612 if (v == w) {
613 if (op == Py_EQ)
614 return 1;
615 else if (op == Py_NE)
616 return 0;
617 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 res = PyObject_RichCompare(v, w, op);
620 if (res == NULL)
621 return -1;
622 if (PyBool_Check(res))
623 ok = (res == Py_True);
624 else
625 ok = PyObject_IsTrue(res);
626 Py_DECREF(res);
627 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000628}
Fred Drake13634cf2000-06-29 19:17:04 +0000629
630/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000632
633 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
634*/
635
Mark Dickinsondc787d22010-05-23 13:33:13 +0000636/* For numeric types, the hash of a number x is based on the reduction
637 of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
638 hash(x) == hash(y) whenever x and y are numerically equal, even if
639 x and y have different types.
640
641 A quick summary of the hashing strategy:
642
643 (1) First define the 'reduction of x modulo P' for any rational
644 number x; this is a standard extension of the usual notion of
645 reduction modulo P for integers. If x == p/q (written in lowest
646 terms), the reduction is interpreted as the reduction of p times
647 the inverse of the reduction of q, all modulo P; if q is exactly
648 divisible by P then define the reduction to be infinity. So we've
649 got a well-defined map
650
651 reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
652
653 (2) Now for a rational number x, define hash(x) by:
654
655 reduce(x) if x >= 0
656 -reduce(-x) if x < 0
657
658 If the result of the reduction is infinity (this is impossible for
659 integers, floats and Decimals) then use the predefined hash value
660 _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
661 _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
662 hashes of float and Decimal infinities and nans.
663
664 A selling point for the above strategy is that it makes it possible
665 to compute hashes of decimal and binary floating-point numbers
666 efficiently, even if the exponent of the binary or decimal number
667 is large. The key point is that
668
669 reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
670
671 provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
672 binary or decimal float is never infinity, since the denominator is a power
673 of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
674 for nonnegative x,
675
676 reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
677
678 reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
679
680 and reduce(10**e) can be computed efficiently by the usual modular
681 exponentiation algorithm. For reduce(2**e) it's even better: since
682 P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
683 by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
684
685 */
686
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000687Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000688_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000689{
Mark Dickinsondc787d22010-05-23 13:33:13 +0000690 int e, sign;
691 double m;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000692 Py_uhash_t x, y;
Tim Peters39dce292000-08-15 03:34:48 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (!Py_IS_FINITE(v)) {
695 if (Py_IS_INFINITY(v))
Mark Dickinsondc787d22010-05-23 13:33:13 +0000696 return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 else
Mark Dickinsondc787d22010-05-23 13:33:13 +0000698 return _PyHASH_NAN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000700
701 m = frexp(v, &e);
702
703 sign = 1;
704 if (m < 0) {
705 sign = -1;
706 m = -m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000708
709 /* process 28 bits at a time; this should work well both for binary
710 and hexadecimal floating point. */
711 x = 0;
712 while (m) {
713 x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
714 m *= 268435456.0; /* 2**28 */
715 e -= 28;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000716 y = (Py_uhash_t)m; /* pull out integer part */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000717 m -= y;
718 x += y;
719 if (x >= _PyHASH_MODULUS)
720 x -= _PyHASH_MODULUS;
721 }
722
723 /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
724 e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
725 x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
726
727 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000728 if (x == (Py_uhash_t)-1)
729 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000730 return (Py_hash_t)x;
Fred Drake13634cf2000-06-29 19:17:04 +0000731}
732
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000733Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000734_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000735{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000736 Py_hash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 size_t y = (size_t)p;
738 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
739 excessive hash collisions for dicts and sets */
740 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000741 x = (Py_hash_t)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (x == -1)
743 x = -2;
744 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000745}
746
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000747Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000748PyObject_HashNotImplemented(PyObject *v)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
751 Py_TYPE(v)->tp_name);
752 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000753}
Fred Drake13634cf2000-06-29 19:17:04 +0000754
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000755Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000756PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyTypeObject *tp = Py_TYPE(v);
759 if (tp->tp_hash != NULL)
760 return (*tp->tp_hash)(v);
761 /* To keep to the general practice that inheriting
762 * solely from object in C code should work without
763 * an explicit call to PyType_Ready, we implicitly call
764 * PyType_Ready here and then check the tp_hash slot again
765 */
766 if (tp->tp_dict == NULL) {
767 if (PyType_Ready(tp) < 0)
768 return -1;
769 if (tp->tp_hash != NULL)
770 return (*tp->tp_hash)(v);
771 }
772 /* Otherwise, the object can't be hashed */
773 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000774}
775
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000777PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (Py_TYPE(v)->tp_getattr != NULL)
782 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
783 w = PyUnicode_InternFromString(name);
784 if (w == NULL)
785 return NULL;
786 res = PyObject_GetAttr(v, w);
787 Py_XDECREF(w);
788 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000789}
790
791int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000792PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyObject *res = PyObject_GetAttrString(v, name);
795 if (res != NULL) {
796 Py_DECREF(res);
797 return 1;
798 }
799 PyErr_Clear();
800 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000801}
802
803int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000804PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject *s;
807 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (Py_TYPE(v)->tp_setattr != NULL)
810 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
811 s = PyUnicode_InternFromString(name);
812 if (s == NULL)
813 return -1;
814 res = PyObject_SetAttr(v, s, w);
815 Py_XDECREF(s);
816 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000817}
818
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000819PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000820PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (!PyUnicode_Check(name)) {
825 PyErr_Format(PyExc_TypeError,
826 "attribute name must be string, not '%.200s'",
827 name->ob_type->tp_name);
828 return NULL;
829 }
830 if (tp->tp_getattro != NULL)
831 return (*tp->tp_getattro)(v, name);
832 if (tp->tp_getattr != NULL) {
833 char *name_str = _PyUnicode_AsString(name);
834 if (name_str == NULL)
835 return NULL;
836 return (*tp->tp_getattr)(v, name_str);
837 }
838 PyErr_Format(PyExc_AttributeError,
839 "'%.50s' object has no attribute '%U'",
840 tp->tp_name, name);
841 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000842}
843
844int
Fred Drake100814d2000-07-09 15:48:49 +0000845PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 PyObject *res = PyObject_GetAttr(v, name);
848 if (res != NULL) {
849 Py_DECREF(res);
850 return 1;
851 }
852 PyErr_Clear();
853 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000854}
855
856int
Fred Drake100814d2000-07-09 15:48:49 +0000857PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyTypeObject *tp = Py_TYPE(v);
860 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (!PyUnicode_Check(name)) {
863 PyErr_Format(PyExc_TypeError,
864 "attribute name must be string, not '%.200s'",
865 name->ob_type->tp_name);
866 return -1;
867 }
868 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyUnicode_InternInPlace(&name);
871 if (tp->tp_setattro != NULL) {
872 err = (*tp->tp_setattro)(v, name, value);
873 Py_DECREF(name);
874 return err;
875 }
876 if (tp->tp_setattr != NULL) {
877 char *name_str = _PyUnicode_AsString(name);
878 if (name_str == NULL)
879 return -1;
880 err = (*tp->tp_setattr)(v, name_str, value);
881 Py_DECREF(name);
882 return err;
883 }
884 Py_DECREF(name);
885 assert(name->ob_refcnt >= 1);
886 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
887 PyErr_Format(PyExc_TypeError,
888 "'%.100s' object has no attributes "
889 "(%s .%U)",
890 tp->tp_name,
891 value==NULL ? "del" : "assign to",
892 name);
893 else
894 PyErr_Format(PyExc_TypeError,
895 "'%.100s' object has only read-only attributes "
896 "(%s .%U)",
897 tp->tp_name,
898 value==NULL ? "del" : "assign to",
899 name);
900 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901}
902
903/* Helper to get a pointer to an object's __dict__ slot, if any */
904
905PyObject **
906_PyObject_GetDictPtr(PyObject *obj)
907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 Py_ssize_t dictoffset;
909 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 dictoffset = tp->tp_dictoffset;
912 if (dictoffset == 0)
913 return NULL;
914 if (dictoffset < 0) {
915 Py_ssize_t tsize;
916 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 tsize = ((PyVarObject *)obj)->ob_size;
919 if (tsize < 0)
920 tsize = -tsize;
921 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 dictoffset += (long)size;
924 assert(dictoffset > 0);
925 assert(dictoffset % SIZEOF_VOID_P == 0);
926 }
927 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000928}
929
Tim Peters6d6c1a32001-08-02 04:15:00 +0000930PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +0000931PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +0000932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 Py_INCREF(obj);
934 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +0000935}
936
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +0000937/* Helper used when the __next__ method is removed from a type:
938 tp_iternext is never NULL and can be safely called without checking
939 on every iteration.
940 */
941
942PyObject *
943_PyObject_NextNotImplemented(PyObject *self)
944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyErr_Format(PyExc_TypeError,
946 "'%.200s' object is not iterable",
947 Py_TYPE(self)->tp_name);
948 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +0000949}
950
Michael W. Hudson1593f502004-09-14 17:09:47 +0000951/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
952
Raymond Hettinger01538262003-03-17 08:24:35 +0000953PyObject *
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000954_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 PyTypeObject *tp = Py_TYPE(obj);
957 PyObject *descr = NULL;
958 PyObject *res = NULL;
959 descrgetfunc f;
960 Py_ssize_t dictoffset;
961 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (!PyUnicode_Check(name)){
964 PyErr_Format(PyExc_TypeError,
965 "attribute name must be string, not '%.200s'",
966 name->ob_type->tp_name);
967 return NULL;
968 }
969 else
970 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (tp->tp_dict == NULL) {
973 if (PyType_Ready(tp) < 0)
974 goto done;
975 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 descr = _PyType_Lookup(tp, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 f = NULL;
981 if (descr != NULL) {
982 f = descr->ob_type->tp_descr_get;
983 if (f != NULL && PyDescr_IsData(descr)) {
984 res = f(descr, obj, (PyObject *)obj->ob_type);
985 Py_DECREF(descr);
986 goto done;
987 }
988 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000990 if (dict == NULL) {
991 /* Inline _PyObject_GetDictPtr */
992 dictoffset = tp->tp_dictoffset;
993 if (dictoffset != 0) {
994 if (dictoffset < 0) {
995 Py_ssize_t tsize;
996 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +0000997
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000998 tsize = ((PyVarObject *)obj)->ob_size;
999 if (tsize < 0)
1000 tsize = -tsize;
1001 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001002
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001003 dictoffset += (long)size;
1004 assert(dictoffset > 0);
1005 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001007 dictptr = (PyObject **) ((char *)obj + dictoffset);
1008 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 }
1010 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001011 if (dict != NULL) {
1012 Py_INCREF(dict);
1013 res = PyDict_GetItem(dict, name);
1014 if (res != NULL) {
1015 Py_INCREF(res);
1016 Py_XDECREF(descr);
1017 Py_DECREF(dict);
1018 goto done;
1019 }
1020 Py_DECREF(dict);
1021 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (f != NULL) {
1024 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1025 Py_DECREF(descr);
1026 goto done;
1027 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (descr != NULL) {
1030 res = descr;
1031 /* descr was already increfed above */
1032 goto done;
1033 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyErr_Format(PyExc_AttributeError,
1036 "'%.50s' object has no attribute '%U'",
1037 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001038 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 Py_DECREF(name);
1040 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041}
1042
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001043PyObject *
1044PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1045{
1046 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1047}
1048
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001050_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1051 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyTypeObject *tp = Py_TYPE(obj);
1054 PyObject *descr;
1055 descrsetfunc f;
1056 PyObject **dictptr;
1057 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (!PyUnicode_Check(name)){
1060 PyErr_Format(PyExc_TypeError,
1061 "attribute name must be string, not '%.200s'",
1062 name->ob_type->tp_name);
1063 return -1;
1064 }
1065 else
1066 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (tp->tp_dict == NULL) {
1069 if (PyType_Ready(tp) < 0)
1070 goto done;
1071 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 descr = _PyType_Lookup(tp, name);
1074 f = NULL;
1075 if (descr != NULL) {
1076 f = descr->ob_type->tp_descr_set;
1077 if (f != NULL && PyDescr_IsData(descr)) {
1078 res = f(descr, obj, value);
1079 goto done;
1080 }
1081 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001083 if (dict == NULL) {
1084 dictptr = _PyObject_GetDictPtr(obj);
1085 if (dictptr != NULL) {
1086 dict = *dictptr;
1087 if (dict == NULL && value != NULL) {
1088 dict = PyDict_New();
1089 if (dict == NULL)
1090 goto done;
1091 *dictptr = dict;
1092 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001094 }
1095 if (dict != NULL) {
1096 Py_INCREF(dict);
1097 if (value == NULL)
1098 res = PyDict_DelItem(dict, name);
1099 else
1100 res = PyDict_SetItem(dict, name, value);
1101 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1102 PyErr_SetObject(PyExc_AttributeError, name);
1103 Py_DECREF(dict);
1104 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (f != NULL) {
1108 res = f(descr, obj, value);
1109 goto done;
1110 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (descr == NULL) {
1113 PyErr_Format(PyExc_AttributeError,
1114 "'%.100s' object has no attribute '%U'",
1115 tp->tp_name, name);
1116 goto done;
1117 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 PyErr_Format(PyExc_AttributeError,
1120 "'%.50s' object attribute '%U' is read-only",
1121 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001122 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 Py_DECREF(name);
1124 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001125}
1126
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001127int
1128PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1129{
1130 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1131}
1132
1133
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001134/* Test a value used as condition, e.g., in a for or if statement.
1135 Return -1 if an error occurred */
1136
1137int
Fred Drake100814d2000-07-09 15:48:49 +00001138PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 Py_ssize_t res;
1141 if (v == Py_True)
1142 return 1;
1143 if (v == Py_False)
1144 return 0;
1145 if (v == Py_None)
1146 return 0;
1147 else if (v->ob_type->tp_as_number != NULL &&
1148 v->ob_type->tp_as_number->nb_bool != NULL)
1149 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1150 else if (v->ob_type->tp_as_mapping != NULL &&
1151 v->ob_type->tp_as_mapping->mp_length != NULL)
1152 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1153 else if (v->ob_type->tp_as_sequence != NULL &&
1154 v->ob_type->tp_as_sequence->sq_length != NULL)
1155 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1156 else
1157 return 1;
1158 /* if it is negative, it should be either -1 or -2 */
1159 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001160}
1161
Tim Peters803526b2002-07-07 05:13:56 +00001162/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001163 Return -1 if an error occurred */
1164
1165int
Fred Drake100814d2000-07-09 15:48:49 +00001166PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 int res;
1169 res = PyObject_IsTrue(v);
1170 if (res < 0)
1171 return res;
1172 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001173}
1174
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001175/* Test whether an object can be called */
1176
1177int
Fred Drake100814d2000-07-09 15:48:49 +00001178PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (x == NULL)
1181 return 0;
1182 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001183}
1184
Georg Brandle32b4222007-03-10 22:13:27 +00001185/* ------------------------- PyObject_Dir() helpers ------------------------- */
1186
Tim Peters7eea37e2001-09-04 22:08:56 +00001187/* Helper for PyObject_Dir.
1188 Merge the __dict__ of aclass into dict, and recursively also all
1189 the __dict__s of aclass's base classes. The order of merging isn't
1190 defined, as it's expected that only the final set of dict keys is
1191 interesting.
1192 Return 0 on success, -1 on error.
1193*/
1194
1195static int
1196merge_class_dict(PyObject* dict, PyObject* aclass)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyObject *classdict;
1199 PyObject *bases;
Tim Peters7eea37e2001-09-04 22:08:56 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 assert(PyDict_Check(dict));
1202 assert(aclass);
Tim Peters7eea37e2001-09-04 22:08:56 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Merge in the type's dict (if any). */
1205 classdict = PyObject_GetAttrString(aclass, "__dict__");
1206 if (classdict == NULL)
1207 PyErr_Clear();
1208 else {
1209 int status = PyDict_Update(dict, classdict);
1210 Py_DECREF(classdict);
1211 if (status < 0)
1212 return -1;
1213 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 /* Recursively merge in the base types' (if any) dicts. */
1216 bases = PyObject_GetAttrString(aclass, "__bases__");
1217 if (bases == NULL)
1218 PyErr_Clear();
1219 else {
1220 /* We have no guarantee that bases is a real tuple */
1221 Py_ssize_t i, n;
1222 n = PySequence_Size(bases); /* This better be right */
1223 if (n < 0)
1224 PyErr_Clear();
1225 else {
1226 for (i = 0; i < n; i++) {
1227 int status;
1228 PyObject *base = PySequence_GetItem(bases, i);
1229 if (base == NULL) {
1230 Py_DECREF(bases);
1231 return -1;
1232 }
1233 status = merge_class_dict(dict, base);
1234 Py_DECREF(base);
1235 if (status < 0) {
1236 Py_DECREF(bases);
1237 return -1;
1238 }
1239 }
1240 }
1241 Py_DECREF(bases);
1242 }
1243 return 0;
Tim Peters7eea37e2001-09-04 22:08:56 +00001244}
1245
Georg Brandle32b4222007-03-10 22:13:27 +00001246/* Helper for PyObject_Dir without arguments: returns the local scope. */
1247static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001248_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 PyObject *names;
1251 PyObject *locals = PyEval_GetLocals();
Tim Peters305b5852001-09-17 02:38:46 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (locals == NULL) {
1254 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1255 return NULL;
1256 }
Tim Peters305b5852001-09-17 02:38:46 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 names = PyMapping_Keys(locals);
1259 if (!names)
1260 return NULL;
1261 if (!PyList_Check(names)) {
1262 PyErr_Format(PyExc_TypeError,
1263 "dir(): expected keys() of locals to be a list, "
1264 "not '%.200s'", Py_TYPE(names)->tp_name);
1265 Py_DECREF(names);
1266 return NULL;
1267 }
1268 /* the locals don't need to be DECREF'd */
1269 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001270}
1271
1272/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
Guido van Rossum98297ee2007-11-06 21:34:58 +00001273 We deliberately don't suck up its __class__, as methods belonging to the
1274 metaclass would probably be more confusing than helpful.
Georg Brandle32b4222007-03-10 22:13:27 +00001275*/
Guido van Rossum98297ee2007-11-06 21:34:58 +00001276static PyObject *
Georg Brandle32b4222007-03-10 22:13:27 +00001277_specialized_dir_type(PyObject *obj)
1278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 PyObject *result = NULL;
1280 PyObject *dict = PyDict_New();
Georg Brandle32b4222007-03-10 22:13:27 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1283 result = PyDict_Keys(dict);
Georg Brandle32b4222007-03-10 22:13:27 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 Py_XDECREF(dict);
1286 return result;
Tim Peters305b5852001-09-17 02:38:46 +00001287}
1288
Georg Brandle32b4222007-03-10 22:13:27 +00001289/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1290static PyObject *
1291_specialized_dir_module(PyObject *obj)
Tim Peters7eea37e2001-09-04 22:08:56 +00001292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyObject *result = NULL;
1294 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Tim Peters7eea37e2001-09-04 22:08:56 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (dict != NULL) {
1297 if (PyDict_Check(dict))
1298 result = PyDict_Keys(dict);
1299 else {
1300 const char *name = PyModule_GetName(obj);
1301 if (name)
1302 PyErr_Format(PyExc_TypeError,
1303 "%.200s.__dict__ is not a dictionary",
1304 name);
1305 }
1306 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 Py_XDECREF(dict);
1309 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001310}
Tim Peters7eea37e2001-09-04 22:08:56 +00001311
Georg Brandle32b4222007-03-10 22:13:27 +00001312/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1313 and recursively up the __class__.__bases__ chain.
1314*/
1315static PyObject *
1316_generic_dir(PyObject *obj)
1317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 PyObject *result = NULL;
1319 PyObject *dict = NULL;
1320 PyObject *itsclass = NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 /* Get __dict__ (which may or may not be a real dict...) */
1323 dict = PyObject_GetAttrString(obj, "__dict__");
1324 if (dict == NULL) {
1325 PyErr_Clear();
1326 dict = PyDict_New();
1327 }
1328 else if (!PyDict_Check(dict)) {
1329 Py_DECREF(dict);
1330 dict = PyDict_New();
1331 }
1332 else {
1333 /* Copy __dict__ to avoid mutating it. */
1334 PyObject *temp = PyDict_Copy(dict);
1335 Py_DECREF(dict);
1336 dict = temp;
1337 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (dict == NULL)
1340 goto error;
Tim Peters7eea37e2001-09-04 22:08:56 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 /* Merge in attrs reachable from its class. */
1343 itsclass = PyObject_GetAttrString(obj, "__class__");
1344 if (itsclass == NULL)
1345 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1346 __class__ exists? */
1347 PyErr_Clear();
1348 else {
1349 if (merge_class_dict(dict, itsclass) != 0)
1350 goto error;
1351 }
Georg Brandle32b4222007-03-10 22:13:27 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 result = PyDict_Keys(dict);
1354 /* fall through */
Georg Brandle32b4222007-03-10 22:13:27 +00001355error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 Py_XDECREF(itsclass);
1357 Py_XDECREF(dict);
1358 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001359}
1360
1361/* Helper for PyObject_Dir: object introspection.
1362 This calls one of the above specialized versions if no __dir__ method
1363 exists. */
1364static PyObject *
1365_dir_object(PyObject *obj)
1366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 PyObject * result = NULL;
1368 PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type,
1369 "__dir__");
Georg Brandle32b4222007-03-10 22:13:27 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 assert(obj);
1372 if (dirfunc == NULL) {
1373 /* use default implementation */
1374 PyErr_Clear();
1375 if (PyModule_Check(obj))
1376 result = _specialized_dir_module(obj);
1377 else if (PyType_Check(obj))
1378 result = _specialized_dir_type(obj);
1379 else
1380 result = _generic_dir(obj);
1381 }
1382 else {
1383 /* use __dir__ */
1384 result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
1385 Py_DECREF(dirfunc);
1386 if (result == NULL)
1387 return NULL;
Georg Brandle32b4222007-03-10 22:13:27 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* result must be a list */
1390 /* XXX(gbrandl): could also check if all items are strings */
1391 if (!PyList_Check(result)) {
1392 PyErr_Format(PyExc_TypeError,
1393 "__dir__() must return a list, not %.200s",
1394 Py_TYPE(result)->tp_name);
1395 Py_DECREF(result);
1396 result = NULL;
1397 }
1398 }
Georg Brandle32b4222007-03-10 22:13:27 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001401}
1402
1403/* Implementation of dir() -- if obj is NULL, returns the names in the current
1404 (local) scope. Otherwise, performs introspection of the object: returns a
1405 sorted list of attribute names (supposedly) accessible from the object
1406*/
1407PyObject *
1408PyObject_Dir(PyObject *obj)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyObject * result;
Georg Brandle32b4222007-03-10 22:13:27 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (obj == NULL)
1413 /* no object -- introspect the locals */
1414 result = _dir_locals();
1415 else
1416 /* object -- introspect the object */
1417 result = _dir_object(obj);
Georg Brandle32b4222007-03-10 22:13:27 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 assert(result == NULL || PyList_Check(result));
Georg Brandle32b4222007-03-10 22:13:27 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (result != NULL && PyList_Sort(result) != 0) {
1422 /* sorting the list failed */
1423 Py_DECREF(result);
1424 result = NULL;
1425 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 return result;
Tim Peters7eea37e2001-09-04 22:08:56 +00001428}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001429
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001430/*
1431NoObject is usable as a non-NULL undefined value, used by the macro None.
1432There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001433so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001434(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001435*/
1436
Guido van Rossum0c182a11992-03-27 17:26:13 +00001437/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001438static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001439none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001442}
1443
Barry Warsaw9bf16442001-01-23 16:24:35 +00001444/* ARGUSED */
1445static void
Tim Peters803526b2002-07-07 05:13:56 +00001446none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 /* This should never get called, but we also don't want to SEGV if
1449 * we accidentally decref None out of existence.
1450 */
1451 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001452}
1453
1454
Guido van Rossumba21a492001-08-16 08:17:26 +00001455static PyTypeObject PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1457 "NoneType",
1458 0,
1459 0,
1460 none_dealloc, /*tp_dealloc*/ /*never called*/
1461 0, /*tp_print*/
1462 0, /*tp_getattr*/
1463 0, /*tp_setattr*/
1464 0, /*tp_reserved*/
1465 none_repr, /*tp_repr*/
1466 0, /*tp_as_number*/
1467 0, /*tp_as_sequence*/
1468 0, /*tp_as_mapping*/
1469 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001470};
1471
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001472PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001473 _PyObject_EXTRA_INIT
1474 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001475};
1476
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001477/* NotImplemented is an object that can be used to signal that an
1478 operation is not implemented for the given type combination. */
1479
1480static PyObject *
1481NotImplemented_repr(PyObject *op)
1482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001484}
1485
1486static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1488 "NotImplementedType",
1489 0,
1490 0,
1491 none_dealloc, /*tp_dealloc*/ /*never called*/
1492 0, /*tp_print*/
1493 0, /*tp_getattr*/
1494 0, /*tp_setattr*/
1495 0, /*tp_reserved*/
1496 NotImplemented_repr, /*tp_repr*/
1497 0, /*tp_as_number*/
1498 0, /*tp_as_sequence*/
1499 0, /*tp_as_mapping*/
1500 0, /*tp_hash */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001501};
1502
1503PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 _PyObject_EXTRA_INIT
1505 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001506};
1507
Guido van Rossumba21a492001-08-16 08:17:26 +00001508void
1509_Py_ReadyTypes(void)
1510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (PyType_Ready(&PyType_Type) < 0)
1512 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1515 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1518 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1521 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (PyType_Ready(&PyBool_Type) < 0)
1524 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (PyType_Ready(&PyByteArray_Type) < 0)
1527 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (PyType_Ready(&PyBytes_Type) < 0)
1530 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (PyType_Ready(&PyList_Type) < 0)
1533 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (PyType_Ready(&PyNone_Type) < 0)
1536 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1539 Py_FatalError("Can't initialize type(Ellipsis)");
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1542 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 if (PyType_Ready(&PyTraceBack_Type) < 0)
1545 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 if (PyType_Ready(&PySuper_Type) < 0)
1548 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (PyType_Ready(&PyBaseObject_Type) < 0)
1551 Py_FatalError("Can't initialize object type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 if (PyType_Ready(&PyRange_Type) < 0)
1554 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 if (PyType_Ready(&PyDict_Type) < 0)
1557 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (PyType_Ready(&PySet_Type) < 0)
1560 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (PyType_Ready(&PyUnicode_Type) < 0)
1563 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (PyType_Ready(&PySlice_Type) < 0)
1566 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1569 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (PyType_Ready(&PyComplex_Type) < 0)
1572 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (PyType_Ready(&PyFloat_Type) < 0)
1575 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if (PyType_Ready(&PyLong_Type) < 0)
1578 Py_FatalError("Can't initialize int type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1581 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 if (PyType_Ready(&PyProperty_Type) < 0)
1584 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (PyType_Ready(&PyMemoryView_Type) < 0)
1587 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (PyType_Ready(&PyTuple_Type) < 0)
1590 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (PyType_Ready(&PyEnum_Type) < 0)
1593 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 if (PyType_Ready(&PyReversed_Type) < 0)
1596 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1599 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (PyType_Ready(&PyCode_Type) < 0)
1602 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 if (PyType_Ready(&PyFrame_Type) < 0)
1605 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (PyType_Ready(&PyCFunction_Type) < 0)
1608 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (PyType_Ready(&PyMethod_Type) < 0)
1611 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 if (PyType_Ready(&PyFunction_Type) < 0)
1614 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (PyType_Ready(&PyDictProxy_Type) < 0)
1617 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (PyType_Ready(&PyGen_Type) < 0)
1620 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1623 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1626 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (PyType_Ready(&PyEllipsis_Type) < 0)
1629 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1632 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (PyType_Ready(&PyFilter_Type) < 0)
1635 Py_FatalError("Can't initialize filter type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (PyType_Ready(&PyMap_Type) < 0)
1638 Py_FatalError("Can't initialize map type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (PyType_Ready(&PyZip_Type) < 0)
1641 Py_FatalError("Can't initialize zip type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001642}
1643
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001644
Guido van Rossum84a90321996-05-22 16:34:47 +00001645#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001646
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001647void
Fred Drake100814d2000-07-09 15:48:49 +00001648_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 _Py_INC_REFTOTAL;
1651 op->ob_refcnt = 1;
1652 _Py_AddToAllObjects(op, 1);
1653 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001654}
1655
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001656void
Fred Drake100814d2000-07-09 15:48:49 +00001657_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001658{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001659#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001661#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (op->ob_refcnt < 0)
1663 Py_FatalError("UNREF negative refcnt");
1664 if (op == &refchain ||
1665 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1666 fprintf(stderr, "* ob\n");
1667 _PyObject_Dump(op);
1668 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1669 _PyObject_Dump(op->_ob_prev->_ob_next);
1670 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1671 _PyObject_Dump(op->_ob_next->_ob_prev);
1672 Py_FatalError("UNREF invalid object");
1673 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001674#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1676 if (p == op)
1677 break;
1678 }
1679 if (p == &refchain) /* Not found */
1680 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001681#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 op->_ob_next->_ob_prev = op->_ob_prev;
1683 op->_ob_prev->_ob_next = op->_ob_next;
1684 op->_ob_next = op->_ob_prev = NULL;
1685 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001686}
1687
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001688void
Fred Drake100814d2000-07-09 15:48:49 +00001689_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1692 _Py_ForgetReference(op);
1693 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001694}
1695
Tim Peters269b2a62003-04-17 19:52:29 +00001696/* Print all live objects. Because PyObject_Print is called, the
1697 * interpreter must be in a healthy state.
1698 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001699void
Fred Drake100814d2000-07-09 15:48:49 +00001700_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyObject *op;
1703 fprintf(fp, "Remaining objects:\n");
1704 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1705 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1706 if (PyObject_Print(op, fp, 0) != 0)
1707 PyErr_Clear();
1708 putc('\n', fp);
1709 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001710}
1711
Tim Peters269b2a62003-04-17 19:52:29 +00001712/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1713 * doesn't make any calls to the Python C API, so is always safe to call.
1714 */
1715void
1716_Py_PrintReferenceAddresses(FILE *fp)
1717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyObject *op;
1719 fprintf(fp, "Remaining object addresses:\n");
1720 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1721 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1722 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001723}
1724
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001725PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001726_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 int i, n;
1729 PyObject *t = NULL;
1730 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1733 return NULL;
1734 op = refchain._ob_next;
1735 res = PyList_New(0);
1736 if (res == NULL)
1737 return NULL;
1738 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1739 while (op == self || op == args || op == res || op == t ||
1740 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1741 op = op->_ob_next;
1742 if (op == &refchain)
1743 return res;
1744 }
1745 if (PyList_Append(res, op) < 0) {
1746 Py_DECREF(res);
1747 return NULL;
1748 }
1749 op = op->_ob_next;
1750 }
1751 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001752}
1753
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001754#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001755
Benjamin Petersonb173f782009-05-05 22:31:58 +00001756/* Hack to force loading of pycapsule.o */
1757PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1758
1759
Guido van Rossum84a90321996-05-22 16:34:47 +00001760/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001761Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001762
1763
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001764/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001765
Thomas Wouters334fb892000-07-25 12:56:38 +00001766void *
Fred Drake100814d2000-07-09 15:48:49 +00001767PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001770}
1771
Thomas Wouters334fb892000-07-25 12:56:38 +00001772void *
1773PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001776}
1777
1778void
Thomas Wouters334fb892000-07-25 12:56:38 +00001779PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyMem_FREE(p);
Guido van Rossumb18618d2000-05-03 23:44:39 +00001782}
1783
1784
Guido van Rossum86610361998-04-10 22:32:46 +00001785/* These methods are used to control infinite recursion in repr, str, print,
1786 etc. Container objects that may recursively contain themselves,
1787 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1788 Py_ReprLeave() to avoid infinite recursion.
1789
1790 Py_ReprEnter() returns 0 the first time it is called for a particular
1791 object and 1 every time thereafter. It returns -1 if an exception
1792 occurred. Py_ReprLeave() has no return value.
1793
1794 See dictobject.c and listobject.c for examples of use.
1795*/
1796
1797#define KEY "Py_Repr"
1798
1799int
Fred Drake100814d2000-07-09 15:48:49 +00001800Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 PyObject *dict;
1803 PyObject *list;
1804 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 dict = PyThreadState_GetDict();
1807 if (dict == NULL)
1808 return 0;
1809 list = PyDict_GetItemString(dict, KEY);
1810 if (list == NULL) {
1811 list = PyList_New(0);
1812 if (list == NULL)
1813 return -1;
1814 if (PyDict_SetItemString(dict, KEY, list) < 0)
1815 return -1;
1816 Py_DECREF(list);
1817 }
1818 i = PyList_GET_SIZE(list);
1819 while (--i >= 0) {
1820 if (PyList_GET_ITEM(list, i) == obj)
1821 return 1;
1822 }
1823 PyList_Append(list, obj);
1824 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001825}
1826
1827void
Fred Drake100814d2000-07-09 15:48:49 +00001828Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 PyObject *dict;
1831 PyObject *list;
1832 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 dict = PyThreadState_GetDict();
1835 if (dict == NULL)
1836 return;
1837 list = PyDict_GetItemString(dict, KEY);
1838 if (list == NULL || !PyList_Check(list))
1839 return;
1840 i = PyList_GET_SIZE(list);
1841 /* Count backwards because we always expect obj to be list[-1] */
1842 while (--i >= 0) {
1843 if (PyList_GET_ITEM(list, i) == obj) {
1844 PyList_SetSlice(list, i, i + 1, NULL);
1845 break;
1846 }
1847 }
Guido van Rossum86610361998-04-10 22:32:46 +00001848}
Guido van Rossumd724b232000-03-13 16:01:29 +00001849
Tim Peters803526b2002-07-07 05:13:56 +00001850/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001851
Tim Peters803526b2002-07-07 05:13:56 +00001852/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001853int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001854
Tim Peters803526b2002-07-07 05:13:56 +00001855/* List of objects that still need to be cleaned up, singly linked via their
1856 * gc headers' gc_prev pointers.
1857 */
1858PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001859
Tim Peters803526b2002-07-07 05:13:56 +00001860/* Add op to the _PyTrash_delete_later list. Called when the current
1861 * call-stack depth gets large. op must be a currently untracked gc'ed
1862 * object, with refcount 0. Py_DECREF must already have been called on it.
1863 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001864void
Fred Drake100814d2000-07-09 15:48:49 +00001865_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 assert(PyObject_IS_GC(op));
1868 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1869 assert(op->ob_refcnt == 0);
1870 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
1871 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001872}
1873
Tim Peters803526b2002-07-07 05:13:56 +00001874/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1875 * the call-stack unwinds again.
1876 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001877void
Fred Drake100814d2000-07-09 15:48:49 +00001878_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 while (_PyTrash_delete_later) {
1881 PyObject *op = _PyTrash_delete_later;
1882 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 _PyTrash_delete_later =
1885 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* Call the deallocator directly. This used to try to
1888 * fool Py_DECREF into calling it indirectly, but
1889 * Py_DECREF was already called on this object, and in
1890 * assorted non-release builds calling Py_DECREF again ends
1891 * up distorting allocation statistics.
1892 */
1893 assert(op->ob_refcnt == 0);
1894 ++_PyTrash_delete_nesting;
1895 (*dealloc)(op);
1896 --_PyTrash_delete_nesting;
1897 }
Guido van Rossumd724b232000-03-13 16:01:29 +00001898}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001899
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001900#ifndef Py_TRACE_REFS
1901/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
1902 Define this here, so we can undefine the macro. */
1903#undef _Py_Dealloc
1904PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
1905void
1906_Py_Dealloc(PyObject *op)
1907{
1908 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
1909 (*Py_TYPE(op)->tp_dealloc)(op);
1910}
1911#endif
1912
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001913#ifdef __cplusplus
1914}
1915#endif