blob: 69d5f83a6930594979732eb957b35ca68b5638c3 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Benjamin Peterson722954a2011-06-11 16:33:35 -05002/* Generic object operations; and implementation of None */
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;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (t == NULL)
300 ret = 0;
301 else {
302 fwrite(PyBytes_AS_STRING(t), 1,
303 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000304 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 }
306 }
307 else {
308 PyErr_Format(PyExc_TypeError,
309 "str() or repr() returned '%.100s'",
310 s->ob_type->tp_name);
311 ret = -1;
312 }
313 Py_XDECREF(s);
314 }
315 }
316 if (ret == 0) {
317 if (ferror(fp)) {
318 PyErr_SetFromErrno(PyExc_IOError);
319 clearerr(fp);
320 ret = -1;
321 }
322 }
323 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324}
325
Guido van Rossum38938152006-08-21 23:36:26 +0000326/* For debugging convenience. Set a breakpoint here and call it from your DLL */
327void
Thomas Woutersb2137042007-02-01 18:02:27 +0000328_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000329{
330}
331
Neal Norwitz1a997502003-01-13 20:13:12 +0000332
Barry Warsaw9bf16442001-01-23 16:24:35 +0000333/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000334void
335_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (op == NULL)
338 fprintf(stderr, "NULL\n");
339 else {
Georg Brandldfd73442009-04-05 11:47:34 +0000340#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 PyGILState_STATE gil;
Georg Brandldfd73442009-04-05 11:47:34 +0000342#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 fprintf(stderr, "object : ");
Georg Brandldfd73442009-04-05 11:47:34 +0000344#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 gil = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000346#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 (void)PyObject_Print(op, stderr, 0);
Georg Brandldfd73442009-04-05 11:47:34 +0000348#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 PyGILState_Release(gil);
Georg Brandldfd73442009-04-05 11:47:34 +0000350#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000366 PyObject *res;
367 if (PyErr_CheckSignals())
368 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000369#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (PyOS_CheckStack()) {
371 PyErr_SetString(PyExc_MemoryError, "stack overflow");
372 return NULL;
373 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000374#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (v == NULL)
376 return PyUnicode_FromString("<NULL>");
377 if (Py_TYPE(v)->tp_repr == NULL)
378 return PyUnicode_FromFormat("<%s object at %p>",
379 v->ob_type->tp_name, v);
380 res = (*v->ob_type->tp_repr)(v);
Victor Stinner0a54cf12011-12-01 03:22:44 +0100381 if (res == NULL)
382 return NULL;
383 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 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 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100390#ifndef Py_DEBUG
391 if (PyUnicode_READY(res) < 0)
392 return NULL;
393#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395}
396
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000398PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyObject *res;
401 if (PyErr_CheckSignals())
402 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000403#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (PyOS_CheckStack()) {
405 PyErr_SetString(PyExc_MemoryError, "stack overflow");
406 return NULL;
407 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000408#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (v == NULL)
410 return PyUnicode_FromString("<NULL>");
411 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100412#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100413 if (PyUnicode_READY(v) < 0)
414 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100415#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 Py_INCREF(v);
417 return v;
418 }
419 if (Py_TYPE(v)->tp_str == NULL)
420 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 /* It is possible for a type to have a tp_str representation that loops
423 infinitely. */
424 if (Py_EnterRecursiveCall(" while getting the str of an object"))
425 return NULL;
426 res = (*Py_TYPE(v)->tp_str)(v);
427 Py_LeaveRecursiveCall();
428 if (res == NULL)
429 return NULL;
430 if (!PyUnicode_Check(res)) {
431 PyErr_Format(PyExc_TypeError,
432 "__str__ returned non-string (type %.200s)",
433 Py_TYPE(res)->tp_name);
434 Py_DECREF(res);
435 return NULL;
436 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100437#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100438 if (PyUnicode_READY(res) < 0)
439 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100440#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100441 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000443}
444
Georg Brandl559e5d72008-06-11 18:37:52 +0000445PyObject *
446PyObject_ASCII(PyObject *v)
447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 repr = PyObject_Repr(v);
451 if (repr == NULL)
452 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200455 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_DECREF(repr);
457 if (ascii == NULL)
458 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 res = PyUnicode_DecodeASCII(
461 PyBytes_AS_STRING(ascii),
462 PyBytes_GET_SIZE(ascii),
463 NULL);
464
465 Py_DECREF(ascii);
466 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000467}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000468
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000469PyObject *
470PyObject_Bytes(PyObject *v)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *result, *func;
Benjamin Petersonce798522012-01-22 11:24:29 -0500473 _Py_IDENTIFIER(__bytes__);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (v == NULL)
476 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (PyBytes_CheckExact(v)) {
479 Py_INCREF(v);
480 return v;
481 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000482
Benjamin Petersonce798522012-01-22 11:24:29 -0500483 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (func != NULL) {
485 result = PyObject_CallFunctionObjArgs(func, NULL);
486 Py_DECREF(func);
487 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000488 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000490 PyErr_Format(PyExc_TypeError,
491 "__bytes__ returned non-bytes (type %.200s)",
492 Py_TYPE(result)->tp_name);
493 Py_DECREF(result);
494 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 }
496 return result;
497 }
498 else if (PyErr_Occurred())
499 return NULL;
500 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000501}
502
Mark Dickinsonc008a172009-02-01 13:59:22 +0000503/* For Python 3.0.1 and later, the old three-way comparison has been
504 completely removed in favour of rich comparisons. PyObject_Compare() and
505 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000506 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000507 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000508
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000509 See (*) below for practical amendments.
510
Mark Dickinsonc008a172009-02-01 13:59:22 +0000511 tp_richcompare gets called with a first argument of the appropriate type
512 and a second object of an arbitrary type. We never do any kind of
513 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000514
Mark Dickinsonc008a172009-02-01 13:59:22 +0000515 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000516
517 NULL if an exception occurred
518 NotImplemented if the requested comparison is not implemented
519 any other false value if the requested comparison is false
520 any other true value if the requested comparison is true
521
522 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
523 NotImplemented.
524
525 (*) Practical amendments:
526
527 - If rich comparison returns NotImplemented, == and != are decided by
528 comparing the object pointer (i.e. falling back to the base object
529 implementation).
530
Guido van Rossuma4073002002-05-31 20:03:54 +0000531*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000532
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000533/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000534int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000535
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000536static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000537
538/* Perform a rich comparison, raising TypeError when the requested comparison
539 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000540static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000541do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 richcmpfunc f;
544 PyObject *res;
545 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (v->ob_type != w->ob_type &&
548 PyType_IsSubtype(w->ob_type, v->ob_type) &&
549 (f = w->ob_type->tp_richcompare) != NULL) {
550 checked_reverse_op = 1;
551 res = (*f)(w, v, _Py_SwappedOp[op]);
552 if (res != Py_NotImplemented)
553 return res;
554 Py_DECREF(res);
555 }
556 if ((f = v->ob_type->tp_richcompare) != NULL) {
557 res = (*f)(v, w, op);
558 if (res != Py_NotImplemented)
559 return res;
560 Py_DECREF(res);
561 }
562 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
563 res = (*f)(w, v, _Py_SwappedOp[op]);
564 if (res != Py_NotImplemented)
565 return res;
566 Py_DECREF(res);
567 }
568 /* If neither object implements it, provide a sensible default
569 for == and !=, but raise an exception for ordering. */
570 switch (op) {
571 case Py_EQ:
572 res = (v == w) ? Py_True : Py_False;
573 break;
574 case Py_NE:
575 res = (v != w) ? Py_True : Py_False;
576 break;
577 default:
578 /* XXX Special-case None so it doesn't show as NoneType() */
579 PyErr_Format(PyExc_TypeError,
580 "unorderable types: %.100s() %s %.100s()",
581 v->ob_type->tp_name,
582 opstrings[op],
583 w->ob_type->tp_name);
584 return NULL;
585 }
586 Py_INCREF(res);
587 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000588}
589
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000590/* Perform a rich comparison with object result. This wraps do_richcompare()
591 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000592
Guido van Rossume797ec12001-01-17 15:24:28 +0000593PyObject *
594PyObject_RichCompare(PyObject *v, PyObject *w, int op)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 assert(Py_LT <= op && op <= Py_GE);
599 if (v == NULL || w == NULL) {
600 if (!PyErr_Occurred())
601 PyErr_BadInternalCall();
602 return NULL;
603 }
604 if (Py_EnterRecursiveCall(" in comparison"))
605 return NULL;
606 res = do_richcompare(v, w, op);
607 Py_LeaveRecursiveCall();
608 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000609}
610
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000611/* Perform a rich comparison with integer result. This wraps
612 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000613int
614PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyObject *res;
617 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Quick result when objects are the same.
620 Guarantees that identity implies equality. */
621 if (v == w) {
622 if (op == Py_EQ)
623 return 1;
624 else if (op == Py_NE)
625 return 0;
626 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 res = PyObject_RichCompare(v, w, op);
629 if (res == NULL)
630 return -1;
631 if (PyBool_Check(res))
632 ok = (res == Py_True);
633 else
634 ok = PyObject_IsTrue(res);
635 Py_DECREF(res);
636 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000637}
Fred Drake13634cf2000-06-29 19:17:04 +0000638
639/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000641
642 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
643*/
644
Mark Dickinsondc787d22010-05-23 13:33:13 +0000645/* For numeric types, the hash of a number x is based on the reduction
646 of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
647 hash(x) == hash(y) whenever x and y are numerically equal, even if
648 x and y have different types.
649
650 A quick summary of the hashing strategy:
651
652 (1) First define the 'reduction of x modulo P' for any rational
653 number x; this is a standard extension of the usual notion of
654 reduction modulo P for integers. If x == p/q (written in lowest
655 terms), the reduction is interpreted as the reduction of p times
656 the inverse of the reduction of q, all modulo P; if q is exactly
657 divisible by P then define the reduction to be infinity. So we've
658 got a well-defined map
659
660 reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
661
662 (2) Now for a rational number x, define hash(x) by:
663
664 reduce(x) if x >= 0
665 -reduce(-x) if x < 0
666
667 If the result of the reduction is infinity (this is impossible for
668 integers, floats and Decimals) then use the predefined hash value
669 _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
670 _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
671 hashes of float and Decimal infinities and nans.
672
673 A selling point for the above strategy is that it makes it possible
674 to compute hashes of decimal and binary floating-point numbers
675 efficiently, even if the exponent of the binary or decimal number
676 is large. The key point is that
677
678 reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
679
680 provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
681 binary or decimal float is never infinity, since the denominator is a power
682 of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
683 for nonnegative x,
684
685 reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
686
687 reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
688
689 and reduce(10**e) can be computed efficiently by the usual modular
690 exponentiation algorithm. For reduce(2**e) it's even better: since
691 P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
692 by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
693
694 */
695
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000696Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000697_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000698{
Mark Dickinsondc787d22010-05-23 13:33:13 +0000699 int e, sign;
700 double m;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000701 Py_uhash_t x, y;
Tim Peters39dce292000-08-15 03:34:48 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (!Py_IS_FINITE(v)) {
704 if (Py_IS_INFINITY(v))
Mark Dickinsondc787d22010-05-23 13:33:13 +0000705 return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 else
Mark Dickinsondc787d22010-05-23 13:33:13 +0000707 return _PyHASH_NAN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000709
710 m = frexp(v, &e);
711
712 sign = 1;
713 if (m < 0) {
714 sign = -1;
715 m = -m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000717
718 /* process 28 bits at a time; this should work well both for binary
719 and hexadecimal floating point. */
720 x = 0;
721 while (m) {
722 x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
723 m *= 268435456.0; /* 2**28 */
724 e -= 28;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000725 y = (Py_uhash_t)m; /* pull out integer part */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000726 m -= y;
727 x += y;
728 if (x >= _PyHASH_MODULUS)
729 x -= _PyHASH_MODULUS;
730 }
731
732 /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
733 e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
734 x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
735
736 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000737 if (x == (Py_uhash_t)-1)
738 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000739 return (Py_hash_t)x;
Fred Drake13634cf2000-06-29 19:17:04 +0000740}
741
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000742Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000743_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000744{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000745 Py_hash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 size_t y = (size_t)p;
747 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
748 excessive hash collisions for dicts and sets */
749 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000750 x = (Py_hash_t)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (x == -1)
752 x = -2;
753 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000754}
755
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000756Py_hash_t
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100757_Py_HashBytes(unsigned char *p, Py_ssize_t len)
758{
759 Py_uhash_t x;
760 Py_ssize_t i;
761
Georg Brandl2fb477c2012-02-21 00:33:36 +0100762 /*
763 We make the hash of the empty string be 0, rather than using
764 (prefix ^ suffix), since this slightly obfuscates the hash secret
765 */
Benjamin Petersond9a35912012-02-21 11:12:14 -0500766 assert(_Py_HashSecret_Initialized);
Georg Brandl2fb477c2012-02-21 00:33:36 +0100767 if (len == 0) {
768 return 0;
769 }
770 x = (Py_uhash_t) _Py_HashSecret.prefix;
771 x ^= (Py_uhash_t) *p << 7;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100772 for (i = 0; i < len; i++)
Gregory P. Smithf5b62a92012-01-14 15:45:13 -0800773 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *p++;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100774 x ^= (Py_uhash_t) len;
Georg Brandl2fb477c2012-02-21 00:33:36 +0100775 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100776 if (x == -1)
777 x = -2;
778 return x;
779}
780
781Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000782PyObject_HashNotImplemented(PyObject *v)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
785 Py_TYPE(v)->tp_name);
786 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000787}
Fred Drake13634cf2000-06-29 19:17:04 +0000788
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100789_Py_HashSecret_t _Py_HashSecret;
790
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000791Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000792PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyTypeObject *tp = Py_TYPE(v);
795 if (tp->tp_hash != NULL)
796 return (*tp->tp_hash)(v);
797 /* To keep to the general practice that inheriting
798 * solely from object in C code should work without
799 * an explicit call to PyType_Ready, we implicitly call
800 * PyType_Ready here and then check the tp_hash slot again
801 */
802 if (tp->tp_dict == NULL) {
803 if (PyType_Ready(tp) < 0)
804 return -1;
805 if (tp->tp_hash != NULL)
806 return (*tp->tp_hash)(v);
807 }
808 /* Otherwise, the object can't be hashed */
809 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000810}
811
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000813PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (Py_TYPE(v)->tp_getattr != NULL)
818 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
819 w = PyUnicode_InternFromString(name);
820 if (w == NULL)
821 return NULL;
822 res = PyObject_GetAttr(v, w);
823 Py_XDECREF(w);
824 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000825}
826
827int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000828PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *res = PyObject_GetAttrString(v, name);
831 if (res != NULL) {
832 Py_DECREF(res);
833 return 1;
834 }
835 PyErr_Clear();
836 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000837}
838
839int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000840PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyObject *s;
843 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (Py_TYPE(v)->tp_setattr != NULL)
846 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
847 s = PyUnicode_InternFromString(name);
848 if (s == NULL)
849 return -1;
850 res = PyObject_SetAttr(v, s, w);
851 Py_XDECREF(s);
852 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000853}
854
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500855int
856_PyObject_IsAbstract(PyObject *obj)
857{
858 int res;
859 PyObject* isabstract;
860 _Py_IDENTIFIER(__isabstractmethod__);
861
862 if (obj == NULL)
863 return 0;
864
865 isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__);
866 if (isabstract == NULL) {
867 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
868 PyErr_Clear();
869 return 0;
870 }
871 return -1;
872 }
873 res = PyObject_IsTrue(isabstract);
874 Py_DECREF(isabstract);
875 return res;
876}
877
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000878PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200879_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
880{
881 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100882 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200883 if (!oname)
884 return NULL;
885 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200886 return result;
887}
888
889int
890_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
891{
892 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100893 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200894 if (!oname)
895 return -1;
896 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200897 return result;
898}
899
900int
901_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
902{
903 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100904 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200905 if (!oname)
906 return -1;
907 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200908 return result;
909}
910
911PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000912PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (!PyUnicode_Check(name)) {
917 PyErr_Format(PyExc_TypeError,
918 "attribute name must be string, not '%.200s'",
919 name->ob_type->tp_name);
920 return NULL;
921 }
922 if (tp->tp_getattro != NULL)
923 return (*tp->tp_getattro)(v, name);
924 if (tp->tp_getattr != NULL) {
925 char *name_str = _PyUnicode_AsString(name);
926 if (name_str == NULL)
927 return NULL;
928 return (*tp->tp_getattr)(v, name_str);
929 }
930 PyErr_Format(PyExc_AttributeError,
931 "'%.50s' object has no attribute '%U'",
932 tp->tp_name, name);
933 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000934}
935
936int
Fred Drake100814d2000-07-09 15:48:49 +0000937PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject *res = PyObject_GetAttr(v, name);
940 if (res != NULL) {
941 Py_DECREF(res);
942 return 1;
943 }
944 PyErr_Clear();
945 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000946}
947
948int
Fred Drake100814d2000-07-09 15:48:49 +0000949PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyTypeObject *tp = Py_TYPE(v);
952 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (!PyUnicode_Check(name)) {
955 PyErr_Format(PyExc_TypeError,
956 "attribute name must be string, not '%.200s'",
957 name->ob_type->tp_name);
958 return -1;
959 }
960 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 PyUnicode_InternInPlace(&name);
963 if (tp->tp_setattro != NULL) {
964 err = (*tp->tp_setattro)(v, name, value);
965 Py_DECREF(name);
966 return err;
967 }
968 if (tp->tp_setattr != NULL) {
969 char *name_str = _PyUnicode_AsString(name);
970 if (name_str == NULL)
971 return -1;
972 err = (*tp->tp_setattr)(v, name_str, value);
973 Py_DECREF(name);
974 return err;
975 }
976 Py_DECREF(name);
977 assert(name->ob_refcnt >= 1);
978 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
979 PyErr_Format(PyExc_TypeError,
980 "'%.100s' object has no attributes "
981 "(%s .%U)",
982 tp->tp_name,
983 value==NULL ? "del" : "assign to",
984 name);
985 else
986 PyErr_Format(PyExc_TypeError,
987 "'%.100s' object has only read-only attributes "
988 "(%s .%U)",
989 tp->tp_name,
990 value==NULL ? "del" : "assign to",
991 name);
992 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993}
994
995/* Helper to get a pointer to an object's __dict__ slot, if any */
996
997PyObject **
998_PyObject_GetDictPtr(PyObject *obj)
999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Py_ssize_t dictoffset;
1001 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 dictoffset = tp->tp_dictoffset;
1004 if (dictoffset == 0)
1005 return NULL;
1006 if (dictoffset < 0) {
1007 Py_ssize_t tsize;
1008 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 tsize = ((PyVarObject *)obj)->ob_size;
1011 if (tsize < 0)
1012 tsize = -tsize;
1013 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 dictoffset += (long)size;
1016 assert(dictoffset > 0);
1017 assert(dictoffset % SIZEOF_VOID_P == 0);
1018 }
1019 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001020}
1021
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001023PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 Py_INCREF(obj);
1026 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001027}
1028
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001029/* Helper used when the __next__ method is removed from a type:
1030 tp_iternext is never NULL and can be safely called without checking
1031 on every iteration.
1032 */
1033
1034PyObject *
1035_PyObject_NextNotImplemented(PyObject *self)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyErr_Format(PyExc_TypeError,
1038 "'%.200s' object is not iterable",
1039 Py_TYPE(self)->tp_name);
1040 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001041}
1042
Michael W. Hudson1593f502004-09-14 17:09:47 +00001043/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1044
Raymond Hettinger01538262003-03-17 08:24:35 +00001045PyObject *
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001046_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyTypeObject *tp = Py_TYPE(obj);
1049 PyObject *descr = NULL;
1050 PyObject *res = NULL;
1051 descrgetfunc f;
1052 Py_ssize_t dictoffset;
1053 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (!PyUnicode_Check(name)){
1056 PyErr_Format(PyExc_TypeError,
1057 "attribute name must be string, not '%.200s'",
1058 name->ob_type->tp_name);
1059 return NULL;
1060 }
1061 else
1062 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (tp->tp_dict == NULL) {
1065 if (PyType_Ready(tp) < 0)
1066 goto done;
1067 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 descr = _PyType_Lookup(tp, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 f = NULL;
1073 if (descr != NULL) {
1074 f = descr->ob_type->tp_descr_get;
1075 if (f != NULL && PyDescr_IsData(descr)) {
1076 res = f(descr, obj, (PyObject *)obj->ob_type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 goto done;
1078 }
1079 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001080
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001081 if (dict == NULL) {
1082 /* Inline _PyObject_GetDictPtr */
1083 dictoffset = tp->tp_dictoffset;
1084 if (dictoffset != 0) {
1085 if (dictoffset < 0) {
1086 Py_ssize_t tsize;
1087 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001088
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001089 tsize = ((PyVarObject *)obj)->ob_size;
1090 if (tsize < 0)
1091 tsize = -tsize;
1092 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001093
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001094 dictoffset += (long)size;
1095 assert(dictoffset > 0);
1096 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001098 dictptr = (PyObject **) ((char *)obj + dictoffset);
1099 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
1101 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001102 if (dict != NULL) {
1103 Py_INCREF(dict);
1104 res = PyDict_GetItem(dict, name);
1105 if (res != NULL) {
1106 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001107 Py_DECREF(dict);
1108 goto done;
1109 }
1110 Py_DECREF(dict);
1111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (f != NULL) {
1114 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 goto done;
1116 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (descr != NULL) {
1119 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001120 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 goto done;
1122 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyErr_Format(PyExc_AttributeError,
1125 "'%.50s' object has no attribute '%U'",
1126 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001127 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001128 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 Py_DECREF(name);
1130 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131}
1132
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001133PyObject *
1134PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1135{
1136 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1137}
1138
Tim Peters6d6c1a32001-08-02 04:15:00 +00001139int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001140_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1141 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyTypeObject *tp = Py_TYPE(obj);
1144 PyObject *descr;
1145 descrsetfunc f;
1146 PyObject **dictptr;
1147 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (!PyUnicode_Check(name)){
1150 PyErr_Format(PyExc_TypeError,
1151 "attribute name must be string, not '%.200s'",
1152 name->ob_type->tp_name);
1153 return -1;
1154 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001156 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1157 return -1;
1158
1159 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001162 Py_XINCREF(descr);
1163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 f = NULL;
1165 if (descr != NULL) {
1166 f = descr->ob_type->tp_descr_set;
1167 if (f != NULL && PyDescr_IsData(descr)) {
1168 res = f(descr, obj, value);
1169 goto done;
1170 }
1171 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001172
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001173 if (dict == NULL) {
1174 dictptr = _PyObject_GetDictPtr(obj);
1175 if (dictptr != NULL) {
1176 dict = *dictptr;
1177 if (dict == NULL && value != NULL) {
1178 dict = PyDict_New();
1179 if (dict == NULL)
1180 goto done;
1181 *dictptr = dict;
1182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001184 }
1185 if (dict != NULL) {
1186 Py_INCREF(dict);
1187 if (value == NULL)
1188 res = PyDict_DelItem(dict, name);
1189 else
1190 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001191 Py_DECREF(dict);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001192 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1193 PyErr_SetObject(PyExc_AttributeError, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001194 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (f != NULL) {
1198 res = f(descr, obj, value);
1199 goto done;
1200 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (descr == NULL) {
1203 PyErr_Format(PyExc_AttributeError,
1204 "'%.100s' object has no attribute '%U'",
1205 tp->tp_name, name);
1206 goto done;
1207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyErr_Format(PyExc_AttributeError,
1210 "'%.50s' object attribute '%U' is read-only",
1211 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001212 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001213 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 Py_DECREF(name);
1215 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001216}
1217
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001218int
1219PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1220{
1221 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1222}
1223
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001224PyObject *
1225PyObject_GenericGetDict(PyObject *obj, void *context)
1226{
1227 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
1228 if (dictptr == NULL) {
1229 PyErr_SetString(PyExc_AttributeError,
1230 "This object has no __dict__");
1231 return NULL;
1232 }
1233 dict = *dictptr;
1234 if (dict == NULL)
1235 *dictptr = dict = PyDict_New();
1236 Py_XINCREF(dict);
1237 return dict;
1238}
1239
1240int
1241PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1242{
1243 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
1244 if (dictptr == NULL) {
1245 PyErr_SetString(PyExc_AttributeError,
1246 "This object has no __dict__");
1247 return -1;
1248 }
1249 if (value == NULL) {
1250 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1251 return -1;
1252 }
1253 if (!PyDict_Check(value)) {
1254 PyErr_Format(PyExc_TypeError,
1255 "__dict__ must be set to a dictionary, "
1256 "not a '%.200s'", Py_TYPE(value)->tp_name);
1257 return -1;
1258 }
1259 dict = *dictptr;
1260 Py_XINCREF(value);
1261 *dictptr = value;
1262 Py_XDECREF(dict);
1263 return 0;
1264}
1265
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001266
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001267/* Test a value used as condition, e.g., in a for or if statement.
1268 Return -1 if an error occurred */
1269
1270int
Fred Drake100814d2000-07-09 15:48:49 +00001271PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 Py_ssize_t res;
1274 if (v == Py_True)
1275 return 1;
1276 if (v == Py_False)
1277 return 0;
1278 if (v == Py_None)
1279 return 0;
1280 else if (v->ob_type->tp_as_number != NULL &&
1281 v->ob_type->tp_as_number->nb_bool != NULL)
1282 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1283 else if (v->ob_type->tp_as_mapping != NULL &&
1284 v->ob_type->tp_as_mapping->mp_length != NULL)
1285 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1286 else if (v->ob_type->tp_as_sequence != NULL &&
1287 v->ob_type->tp_as_sequence->sq_length != NULL)
1288 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1289 else
1290 return 1;
1291 /* if it is negative, it should be either -1 or -2 */
1292 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001293}
1294
Tim Peters803526b2002-07-07 05:13:56 +00001295/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001296 Return -1 if an error occurred */
1297
1298int
Fred Drake100814d2000-07-09 15:48:49 +00001299PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 int res;
1302 res = PyObject_IsTrue(v);
1303 if (res < 0)
1304 return res;
1305 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001306}
1307
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001308/* Test whether an object can be called */
1309
1310int
Fred Drake100814d2000-07-09 15:48:49 +00001311PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (x == NULL)
1314 return 0;
1315 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001316}
1317
Tim Peters7eea37e2001-09-04 22:08:56 +00001318
Georg Brandle32b4222007-03-10 22:13:27 +00001319/* Helper for PyObject_Dir without arguments: returns the local scope. */
1320static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001321_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 PyObject *names;
1324 PyObject *locals = PyEval_GetLocals();
Tim Peters305b5852001-09-17 02:38:46 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (locals == NULL) {
1327 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1328 return NULL;
1329 }
Tim Peters305b5852001-09-17 02:38:46 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 names = PyMapping_Keys(locals);
1332 if (!names)
1333 return NULL;
1334 if (!PyList_Check(names)) {
1335 PyErr_Format(PyExc_TypeError,
1336 "dir(): expected keys() of locals to be a list, "
1337 "not '%.200s'", Py_TYPE(names)->tp_name);
1338 Py_DECREF(names);
1339 return NULL;
1340 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001341 if (PyList_Sort(names)) {
1342 Py_DECREF(names);
1343 return NULL;
1344 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 /* the locals don't need to be DECREF'd */
1346 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001347}
1348
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001349/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001350static PyObject *
1351_dir_object(PyObject *obj)
1352{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001353 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001354 _Py_IDENTIFIER(__dir__);
1355 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 assert(obj);
1358 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001359 if (!PyErr_Occurred())
1360 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1361 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001363 /* use __dir__ */
1364 result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
1365 Py_DECREF(dirfunc);
1366 if (result == NULL)
1367 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001368 /* return sorted(result) */
1369 sorted = PySequence_List(result);
1370 Py_DECREF(result);
1371 if (sorted == NULL)
1372 return NULL;
1373 if (PyList_Sort(sorted)) {
1374 Py_DECREF(sorted);
1375 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001377 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001378}
1379
1380/* Implementation of dir() -- if obj is NULL, returns the names in the current
1381 (local) scope. Otherwise, performs introspection of the object: returns a
1382 sorted list of attribute names (supposedly) accessible from the object
1383*/
1384PyObject *
1385PyObject_Dir(PyObject *obj)
1386{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001387 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001388}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001389
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001390/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001391None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001392There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001393so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001394*/
1395
Guido van Rossum0c182a11992-03-27 17:26:13 +00001396/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001397static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001398none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001401}
1402
Barry Warsaw9bf16442001-01-23 16:24:35 +00001403/* ARGUSED */
1404static void
Tim Peters803526b2002-07-07 05:13:56 +00001405none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 /* This should never get called, but we also don't want to SEGV if
1408 * we accidentally decref None out of existence.
1409 */
1410 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001411}
1412
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001413static PyObject *
1414none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1415{
1416 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1417 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1418 return NULL;
1419 }
1420 Py_RETURN_NONE;
1421}
1422
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001423static int
1424none_bool(PyObject *v)
1425{
1426 return 0;
1427}
1428
1429static PyNumberMethods none_as_number = {
1430 0, /* nb_add */
1431 0, /* nb_subtract */
1432 0, /* nb_multiply */
1433 0, /* nb_remainder */
1434 0, /* nb_divmod */
1435 0, /* nb_power */
1436 0, /* nb_negative */
1437 0, /* nb_positive */
1438 0, /* nb_absolute */
1439 (inquiry)none_bool, /* nb_bool */
1440 0, /* nb_invert */
1441 0, /* nb_lshift */
1442 0, /* nb_rshift */
1443 0, /* nb_and */
1444 0, /* nb_xor */
1445 0, /* nb_or */
1446 0, /* nb_int */
1447 0, /* nb_reserved */
1448 0, /* nb_float */
1449 0, /* nb_inplace_add */
1450 0, /* nb_inplace_subtract */
1451 0, /* nb_inplace_multiply */
1452 0, /* nb_inplace_remainder */
1453 0, /* nb_inplace_power */
1454 0, /* nb_inplace_lshift */
1455 0, /* nb_inplace_rshift */
1456 0, /* nb_inplace_and */
1457 0, /* nb_inplace_xor */
1458 0, /* nb_inplace_or */
1459 0, /* nb_floor_divide */
1460 0, /* nb_true_divide */
1461 0, /* nb_inplace_floor_divide */
1462 0, /* nb_inplace_true_divide */
1463 0, /* nb_index */
1464};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001465
Guido van Rossumba21a492001-08-16 08:17:26 +00001466static PyTypeObject PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1468 "NoneType",
1469 0,
1470 0,
1471 none_dealloc, /*tp_dealloc*/ /*never called*/
1472 0, /*tp_print*/
1473 0, /*tp_getattr*/
1474 0, /*tp_setattr*/
1475 0, /*tp_reserved*/
1476 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001477 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 0, /*tp_as_sequence*/
1479 0, /*tp_as_mapping*/
1480 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001481 0, /*tp_call */
1482 0, /*tp_str */
1483 0, /*tp_getattro */
1484 0, /*tp_setattro */
1485 0, /*tp_as_buffer */
1486 Py_TPFLAGS_DEFAULT, /*tp_flags */
1487 0, /*tp_doc */
1488 0, /*tp_traverse */
1489 0, /*tp_clear */
1490 0, /*tp_richcompare */
1491 0, /*tp_weaklistoffset */
1492 0, /*tp_iter */
1493 0, /*tp_iternext */
1494 0, /*tp_methods */
1495 0, /*tp_members */
1496 0, /*tp_getset */
1497 0, /*tp_base */
1498 0, /*tp_dict */
1499 0, /*tp_descr_get */
1500 0, /*tp_descr_set */
1501 0, /*tp_dictoffset */
1502 0, /*tp_init */
1503 0, /*tp_alloc */
1504 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001505};
1506
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001507PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001508 _PyObject_EXTRA_INIT
1509 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001510};
1511
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001512/* NotImplemented is an object that can be used to signal that an
1513 operation is not implemented for the given type combination. */
1514
1515static PyObject *
1516NotImplemented_repr(PyObject *op)
1517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001519}
1520
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001521static PyObject *
1522notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1523{
1524 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1525 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1526 return NULL;
1527 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001528 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001529}
1530
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001531static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1533 "NotImplementedType",
1534 0,
1535 0,
1536 none_dealloc, /*tp_dealloc*/ /*never called*/
1537 0, /*tp_print*/
1538 0, /*tp_getattr*/
1539 0, /*tp_setattr*/
1540 0, /*tp_reserved*/
1541 NotImplemented_repr, /*tp_repr*/
1542 0, /*tp_as_number*/
1543 0, /*tp_as_sequence*/
1544 0, /*tp_as_mapping*/
1545 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001546 0, /*tp_call */
1547 0, /*tp_str */
1548 0, /*tp_getattro */
1549 0, /*tp_setattro */
1550 0, /*tp_as_buffer */
1551 Py_TPFLAGS_DEFAULT, /*tp_flags */
1552 0, /*tp_doc */
1553 0, /*tp_traverse */
1554 0, /*tp_clear */
1555 0, /*tp_richcompare */
1556 0, /*tp_weaklistoffset */
1557 0, /*tp_iter */
1558 0, /*tp_iternext */
1559 0, /*tp_methods */
1560 0, /*tp_members */
1561 0, /*tp_getset */
1562 0, /*tp_base */
1563 0, /*tp_dict */
1564 0, /*tp_descr_get */
1565 0, /*tp_descr_set */
1566 0, /*tp_dictoffset */
1567 0, /*tp_init */
1568 0, /*tp_alloc */
1569 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001570};
1571
1572PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 _PyObject_EXTRA_INIT
1574 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001575};
1576
Guido van Rossumba21a492001-08-16 08:17:26 +00001577void
1578_Py_ReadyTypes(void)
1579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (PyType_Ready(&PyType_Type) < 0)
1581 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1584 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1587 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1590 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (PyType_Ready(&PyBool_Type) < 0)
1593 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 if (PyType_Ready(&PyByteArray_Type) < 0)
1596 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 if (PyType_Ready(&PyBytes_Type) < 0)
1599 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (PyType_Ready(&PyList_Type) < 0)
1602 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 if (PyType_Ready(&PyNone_Type) < 0)
1605 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1608 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (PyType_Ready(&PyTraceBack_Type) < 0)
1611 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 if (PyType_Ready(&PySuper_Type) < 0)
1614 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (PyType_Ready(&PyBaseObject_Type) < 0)
1617 Py_FatalError("Can't initialize object type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (PyType_Ready(&PyRange_Type) < 0)
1620 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (PyType_Ready(&PyDict_Type) < 0)
1623 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (PyType_Ready(&PySet_Type) < 0)
1626 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (PyType_Ready(&PyUnicode_Type) < 0)
1629 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (PyType_Ready(&PySlice_Type) < 0)
1632 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1635 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (PyType_Ready(&PyComplex_Type) < 0)
1638 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (PyType_Ready(&PyFloat_Type) < 0)
1641 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (PyType_Ready(&PyLong_Type) < 0)
1644 Py_FatalError("Can't initialize int type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1647 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 if (PyType_Ready(&PyProperty_Type) < 0)
1650 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001651
Stefan Krah9a2d99e2012-02-25 12:24:21 +01001652 if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
1653 Py_FatalError("Can't initialize managed buffer type");
1654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 if (PyType_Ready(&PyMemoryView_Type) < 0)
1656 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (PyType_Ready(&PyTuple_Type) < 0)
1659 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (PyType_Ready(&PyEnum_Type) < 0)
1662 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 if (PyType_Ready(&PyReversed_Type) < 0)
1665 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1668 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (PyType_Ready(&PyCode_Type) < 0)
1671 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (PyType_Ready(&PyFrame_Type) < 0)
1674 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 if (PyType_Ready(&PyCFunction_Type) < 0)
1677 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (PyType_Ready(&PyMethod_Type) < 0)
1680 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 if (PyType_Ready(&PyFunction_Type) < 0)
1683 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (PyType_Ready(&PyDictProxy_Type) < 0)
1686 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (PyType_Ready(&PyGen_Type) < 0)
1689 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1692 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1695 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001696
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001697 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1698 Py_FatalError("Can't initialize method wrapper type");
1699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 if (PyType_Ready(&PyEllipsis_Type) < 0)
1701 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1704 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (PyType_Ready(&PyFilter_Type) < 0)
1707 Py_FatalError("Can't initialize filter type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (PyType_Ready(&PyMap_Type) < 0)
1710 Py_FatalError("Can't initialize map type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 if (PyType_Ready(&PyZip_Type) < 0)
1713 Py_FatalError("Can't initialize zip type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001714}
1715
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001716
Guido van Rossum84a90321996-05-22 16:34:47 +00001717#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001718
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001719void
Fred Drake100814d2000-07-09 15:48:49 +00001720_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 _Py_INC_REFTOTAL;
1723 op->ob_refcnt = 1;
1724 _Py_AddToAllObjects(op, 1);
1725 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001726}
1727
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001728void
Fred Drake100814d2000-07-09 15:48:49 +00001729_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001730{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001731#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001733#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (op->ob_refcnt < 0)
1735 Py_FatalError("UNREF negative refcnt");
1736 if (op == &refchain ||
1737 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1738 fprintf(stderr, "* ob\n");
1739 _PyObject_Dump(op);
1740 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1741 _PyObject_Dump(op->_ob_prev->_ob_next);
1742 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1743 _PyObject_Dump(op->_ob_next->_ob_prev);
1744 Py_FatalError("UNREF invalid object");
1745 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001746#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1748 if (p == op)
1749 break;
1750 }
1751 if (p == &refchain) /* Not found */
1752 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001753#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 op->_ob_next->_ob_prev = op->_ob_prev;
1755 op->_ob_prev->_ob_next = op->_ob_next;
1756 op->_ob_next = op->_ob_prev = NULL;
1757 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001758}
1759
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001760void
Fred Drake100814d2000-07-09 15:48:49 +00001761_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1764 _Py_ForgetReference(op);
1765 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001766}
1767
Tim Peters269b2a62003-04-17 19:52:29 +00001768/* Print all live objects. Because PyObject_Print is called, the
1769 * interpreter must be in a healthy state.
1770 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001771void
Fred Drake100814d2000-07-09 15:48:49 +00001772_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyObject *op;
1775 fprintf(fp, "Remaining objects:\n");
1776 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1777 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1778 if (PyObject_Print(op, fp, 0) != 0)
1779 PyErr_Clear();
1780 putc('\n', fp);
1781 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001782}
1783
Tim Peters269b2a62003-04-17 19:52:29 +00001784/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1785 * doesn't make any calls to the Python C API, so is always safe to call.
1786 */
1787void
1788_Py_PrintReferenceAddresses(FILE *fp)
1789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyObject *op;
1791 fprintf(fp, "Remaining object addresses:\n");
1792 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1793 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1794 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001795}
1796
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001797PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001798_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 int i, n;
1801 PyObject *t = NULL;
1802 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1805 return NULL;
1806 op = refchain._ob_next;
1807 res = PyList_New(0);
1808 if (res == NULL)
1809 return NULL;
1810 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1811 while (op == self || op == args || op == res || op == t ||
1812 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1813 op = op->_ob_next;
1814 if (op == &refchain)
1815 return res;
1816 }
1817 if (PyList_Append(res, op) < 0) {
1818 Py_DECREF(res);
1819 return NULL;
1820 }
1821 op = op->_ob_next;
1822 }
1823 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001824}
1825
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001826#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001827
Benjamin Petersonb173f782009-05-05 22:31:58 +00001828/* Hack to force loading of pycapsule.o */
1829PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1830
1831
Guido van Rossum84a90321996-05-22 16:34:47 +00001832/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001833Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001834
1835
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001836/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001837
Thomas Wouters334fb892000-07-25 12:56:38 +00001838void *
Fred Drake100814d2000-07-09 15:48:49 +00001839PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001842}
1843
Thomas Wouters334fb892000-07-25 12:56:38 +00001844void *
1845PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001848}
1849
1850void
Thomas Wouters334fb892000-07-25 12:56:38 +00001851PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PyMem_FREE(p);
Guido van Rossumb18618d2000-05-03 23:44:39 +00001854}
1855
1856
Guido van Rossum86610361998-04-10 22:32:46 +00001857/* These methods are used to control infinite recursion in repr, str, print,
1858 etc. Container objects that may recursively contain themselves,
1859 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1860 Py_ReprLeave() to avoid infinite recursion.
1861
1862 Py_ReprEnter() returns 0 the first time it is called for a particular
1863 object and 1 every time thereafter. It returns -1 if an exception
1864 occurred. Py_ReprLeave() has no return value.
1865
1866 See dictobject.c and listobject.c for examples of use.
1867*/
1868
1869#define KEY "Py_Repr"
1870
1871int
Fred Drake100814d2000-07-09 15:48:49 +00001872Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 PyObject *dict;
1875 PyObject *list;
1876 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 dict = PyThreadState_GetDict();
1879 if (dict == NULL)
1880 return 0;
1881 list = PyDict_GetItemString(dict, KEY);
1882 if (list == NULL) {
1883 list = PyList_New(0);
1884 if (list == NULL)
1885 return -1;
1886 if (PyDict_SetItemString(dict, KEY, list) < 0)
1887 return -1;
1888 Py_DECREF(list);
1889 }
1890 i = PyList_GET_SIZE(list);
1891 while (--i >= 0) {
1892 if (PyList_GET_ITEM(list, i) == obj)
1893 return 1;
1894 }
1895 PyList_Append(list, obj);
1896 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001897}
1898
1899void
Fred Drake100814d2000-07-09 15:48:49 +00001900Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 PyObject *dict;
1903 PyObject *list;
1904 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 dict = PyThreadState_GetDict();
1907 if (dict == NULL)
1908 return;
1909 list = PyDict_GetItemString(dict, KEY);
1910 if (list == NULL || !PyList_Check(list))
1911 return;
1912 i = PyList_GET_SIZE(list);
1913 /* Count backwards because we always expect obj to be list[-1] */
1914 while (--i >= 0) {
1915 if (PyList_GET_ITEM(list, i) == obj) {
1916 PyList_SetSlice(list, i, i + 1, NULL);
1917 break;
1918 }
1919 }
Guido van Rossum86610361998-04-10 22:32:46 +00001920}
Guido van Rossumd724b232000-03-13 16:01:29 +00001921
Tim Peters803526b2002-07-07 05:13:56 +00001922/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001923
Tim Peters803526b2002-07-07 05:13:56 +00001924/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001925int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001926
Tim Peters803526b2002-07-07 05:13:56 +00001927/* List of objects that still need to be cleaned up, singly linked via their
1928 * gc headers' gc_prev pointers.
1929 */
1930PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001931
Tim Peters803526b2002-07-07 05:13:56 +00001932/* Add op to the _PyTrash_delete_later list. Called when the current
1933 * call-stack depth gets large. op must be a currently untracked gc'ed
1934 * object, with refcount 0. Py_DECREF must already have been called on it.
1935 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001936void
Fred Drake100814d2000-07-09 15:48:49 +00001937_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 assert(PyObject_IS_GC(op));
1940 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1941 assert(op->ob_refcnt == 0);
1942 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
1943 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001944}
1945
Tim Peters803526b2002-07-07 05:13:56 +00001946/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1947 * the call-stack unwinds again.
1948 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001949void
Fred Drake100814d2000-07-09 15:48:49 +00001950_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 while (_PyTrash_delete_later) {
1953 PyObject *op = _PyTrash_delete_later;
1954 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 _PyTrash_delete_later =
1957 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 /* Call the deallocator directly. This used to try to
1960 * fool Py_DECREF into calling it indirectly, but
1961 * Py_DECREF was already called on this object, and in
1962 * assorted non-release builds calling Py_DECREF again ends
1963 * up distorting allocation statistics.
1964 */
1965 assert(op->ob_refcnt == 0);
1966 ++_PyTrash_delete_nesting;
1967 (*dealloc)(op);
1968 --_PyTrash_delete_nesting;
1969 }
Guido van Rossumd724b232000-03-13 16:01:29 +00001970}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001971
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001972#ifndef Py_TRACE_REFS
1973/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
1974 Define this here, so we can undefine the macro. */
1975#undef _Py_Dealloc
1976PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
1977void
1978_Py_Dealloc(PyObject *op)
1979{
1980 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
1981 (*Py_TYPE(op)->tp_dealloc)(op);
1982}
1983#endif
1984
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001985#ifdef __cplusplus
1986}
1987#endif