blob: 80111b4ee1ac1aed48ab7253b1a6054adbefc5d8 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum50e9fb92006-08-17 05:42:55 +00005#include "sliceobject.h" /* For PyEllipsis_Type */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#ifdef __cplusplus
8extern "C" {
9#endif
10
Tim Peters34592512002-07-11 06:23:50 +000011#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000012Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013
14Py_ssize_t
15_Py_GetRefTotal(void)
16{
17 PyObject *o;
18 Py_ssize_t total = _Py_RefTotal;
19 /* ignore the references to the dummy object of the dicts and sets
20 because they are not reliable and not useful (now that the
21 hash table code is well-tested) */
22 o = _PyDict_Dummy();
23 if (o != NULL)
24 total -= o->ob_refcnt;
25 o = _PySet_Dummy();
26 if (o != NULL)
27 total -= o->ob_refcnt;
28 return total;
29}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Mark Hammonda2905272002-07-29 13:42:14 +000032int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000033
Guido van Rossum3f5da241990-12-20 15:06:42 +000034/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
35 These are used by the individual routines for object creation.
36 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037
Tim Peters78be7992003-03-23 02:51:01 +000038#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000039/* Head of circular doubly-linked list of all objects. These are linked
40 * together via the _ob_prev and _ob_next members of a PyObject, which
41 * exist only in a Py_TRACE_REFS build.
42 */
Tim Peters78be7992003-03-23 02:51:01 +000043static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000044
Tim Peters7571a0f2003-03-23 17:52:28 +000045/* Insert op at the front of the list of all objects. If force is true,
46 * op is added even if _ob_prev and _ob_next are non-NULL already. If
47 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
48 * force should be true if and only if op points to freshly allocated,
49 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000050 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000051 * Note that objects are normally added to the list via _Py_NewReference,
52 * which is called by PyObject_Init. Not all objects are initialized that
53 * way, though; exceptions include statically allocated type objects, and
54 * statically allocated singletons (like Py_True and Py_None).
55 */
Tim Peters36eb4df2003-03-23 03:33:13 +000056void
Tim Peters7571a0f2003-03-23 17:52:28 +000057_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000058{
Tim Peters7571a0f2003-03-23 17:52:28 +000059#ifdef Py_DEBUG
60 if (!force) {
61 /* If it's initialized memory, op must be in or out of
62 * the list unambiguously.
63 */
64 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
65 }
Tim Peters78be7992003-03-23 02:51:01 +000066#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000067 if (force || op->_ob_prev == NULL) {
68 op->_ob_next = refchain._ob_next;
69 op->_ob_prev = &refchain;
70 refchain._ob_next->_ob_prev = op;
71 refchain._ob_next = op;
72 }
73}
74#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000075
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078/* All types are added to type_list, at least when
79 they get one object created. That makes them
80 immortal, which unfortunately contributes to
81 garbage itself. If unlist_types_without_objects
82 is set, they will be removed from the type_list
83 once the last object is deallocated. */
84int unlist_types_without_objects;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000085extern int tuple_zero_allocs, fast_tuple_allocs;
86extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000087extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000088void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000090{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000092
93 for (tp = type_list; tp; tp = tp->tp_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094 fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000095 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000096 tp->tp_maxalloc);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000097 fprintf(f, "fast tuple allocs: %d, empty: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000098 fast_tuple_allocs, tuple_zero_allocs);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000099 fprintf(f, "fast int allocs: pos: %d, neg: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +0000100 quick_int_allocs, quick_neg_int_allocs);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101 fprintf(f, "null strings: %d, 1-strings: %d\n",
Sjoerd Mullender52c1f511993-10-25 08:40:52 +0000102 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000103}
104
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000105PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000106get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000107{
108 PyTypeObject *tp;
109 PyObject *result;
110 PyObject *v;
111
112 result = PyList_New(0);
113 if (result == NULL)
114 return NULL;
115 for (tp = type_list; tp; tp = tp->tp_next) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000116 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000117 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000118 if (v == NULL) {
119 Py_DECREF(result);
120 return NULL;
121 }
122 if (PyList_Append(result, v) < 0) {
123 Py_DECREF(v);
124 Py_DECREF(result);
125 return NULL;
126 }
127 Py_DECREF(v);
128 }
129 return result;
130}
131
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000132void
Fred Drake100814d2000-07-09 15:48:49 +0000133inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000134{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000135 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000136 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 Py_FatalError("XXX inc_count sanity check");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000139 if (type_list)
140 type_list->tp_prev = tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000141 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000142 /* Note that as of Python 2.2, heap-allocated type objects
143 * can go away, but this code requires that they stay alive
144 * until program exit. That's why we're careful with
145 * refcounts here. type_list gets a new reference to tp,
146 * while ownership of the reference type_list used to hold
147 * (if any) was transferred to tp->tp_next in the line above.
148 * tp is thus effectively immortal after this.
149 */
150 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000151 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000152#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000153 /* Also insert in the doubly-linked list of all objects,
154 * if not already there.
155 */
156 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000157#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000158 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000159 tp->tp_allocs++;
160 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
161 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000162}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163
164void dec_count(PyTypeObject *tp)
165{
166 tp->tp_frees++;
167 if (unlist_types_without_objects &&
168 tp->tp_allocs == tp->tp_frees) {
169 /* unlink the type from type_list */
170 if (tp->tp_prev)
171 tp->tp_prev->tp_next = tp->tp_next;
172 else
173 type_list = tp->tp_next;
174 if (tp->tp_next)
175 tp->tp_next->tp_prev = tp->tp_prev;
176 tp->tp_next = tp->tp_prev = NULL;
177 Py_DECREF(tp);
178 }
179}
180
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000181#endif
182
Tim Peters7c321a82002-07-09 02:57:01 +0000183#ifdef Py_REF_DEBUG
184/* Log a fatal error; doesn't return. */
185void
186_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
187{
188 char buf[300];
189
190 PyOS_snprintf(buf, sizeof(buf),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191 "%s:%i object at %p has negative ref count "
192 "%" PY_FORMAT_SIZE_T "d",
193 fname, lineno, op, op->ob_refcnt);
Tim Peters7c321a82002-07-09 02:57:01 +0000194 Py_FatalError(buf);
195}
196
197#endif /* Py_REF_DEBUG */
198
Thomas Heller1328b522004-04-22 17:23:49 +0000199void
200Py_IncRef(PyObject *o)
201{
202 Py_XINCREF(o);
203}
204
205void
206Py_DecRef(PyObject *o)
207{
208 Py_XDECREF(o);
209}
210
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000212PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000214 if (op == NULL)
215 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000216 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000218 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219 return op;
220}
221
Guido van Rossumb18618d2000-05-03 23:44:39 +0000222PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000224{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000225 if (op == NULL)
226 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227 /* Any changes should be reflected in PyObject_INIT_VAR */
228 op->ob_size = size;
229 op->ob_type = tp;
230 _Py_NewReference((PyObject *)op);
231 return op;
232}
233
234PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000235_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000236{
237 PyObject *op;
238 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
239 if (op == NULL)
240 return PyErr_NoMemory();
241 return PyObject_INIT(op, tp);
242}
243
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000244PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000245_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000247 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000248 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000249 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000251 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000252 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000253}
254
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000255/* for binary compatibility with 2.2 */
256#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000257void
Fred Drake100814d2000-07-09 15:48:49 +0000258_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000259{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000260 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261}
262
Neal Norwitz1a997502003-01-13 20:13:12 +0000263/* Implementation of PyObject_Print with recursion checking */
264static int
265internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266{
Guido van Rossum278ef591991-07-27 21:40:24 +0000267 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000268 if (nesting > 10) {
269 PyErr_SetString(PyExc_RuntimeError, "print recursion");
270 return -1;
271 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000273 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000274#ifdef USE_STACKCHECK
275 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000276 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000277 return -1;
278 }
279#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000280 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000281 if (op == NULL) {
282 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283 }
Guido van Rossum90933611991-06-07 16:10:43 +0000284 else {
285 if (op->ob_refcnt <= 0)
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000286 /* XXX(twouters) cast refcount to long until %zd is
287 universally available */
288 fprintf(fp, "<refcnt %ld at %p>",
289 (long)op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000290 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000291 PyObject *s;
292 if (flags & Py_PRINT_RAW)
293 s = PyObject_Str(op);
294 else
295 s = PyObject_Repr(op);
296 if (s == NULL)
297 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000298 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000299 ret = internal_print(s, fp, Py_PRINT_RAW,
300 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000301 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000302 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000303 }
Guido van Rossum90933611991-06-07 16:10:43 +0000304 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000305 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000306 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000307 if (ret == 0) {
308 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000310 clearerr(fp);
311 ret = -1;
312 }
313 }
314 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315}
316
Neal Norwitz1a997502003-01-13 20:13:12 +0000317int
318PyObject_Print(PyObject *op, FILE *fp, int flags)
319{
320 return internal_print(op, fp, flags, 0);
321}
322
Guido van Rossum38938152006-08-21 23:36:26 +0000323/* For debugging convenience. Set a breakpoint here and call it from your DLL */
324void
325_Py_Break(void)
326{
327}
328
Neal Norwitz1a997502003-01-13 20:13:12 +0000329
Barry Warsaw9bf16442001-01-23 16:24:35 +0000330/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000331void
332_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000333{
Barry Warsaweefb1072001-02-22 22:39:18 +0000334 if (op == NULL)
335 fprintf(stderr, "NULL\n");
336 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000337 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000338 (void)PyObject_Print(op, stderr, 0);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000339 /* XXX(twouters) cast refcount to long until %zd is
340 universally available */
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000341 fprintf(stderr, "\n"
342 "type : %s\n"
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000343 "refcount: %ld\n"
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000344 "address : %p\n",
345 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +0000346 (long)op->ob_refcnt,
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000347 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000348 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000349}
Barry Warsaw903138f2001-01-23 16:33:18 +0000350
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000352PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000354 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000355 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000356#ifdef USE_STACKCHECK
357 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000358 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000359 return NULL;
360 }
361#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000362 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000364 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000365 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000366 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000367 else {
368 PyObject *res;
369 res = (*v->ob_type->tp_repr)(v);
370 if (res == NULL)
371 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000372#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000373 if (PyUnicode_Check(res)) {
374 PyObject* str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000375 str = PyUnicode_AsEncodedString(res, NULL, NULL);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000376 Py_DECREF(res);
377 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000378 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000379 else
380 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000381 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000382#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000383 if (!PyString_Check(res)) {
384 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000385 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000386 res->ob_type->tp_name);
387 Py_DECREF(res);
388 return NULL;
389 }
390 return res;
391 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392}
393
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000395_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000396{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000397 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000398 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000399 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000401 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000402 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000403 return v;
404 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000405#ifdef Py_USING_UNICODE
406 if (PyUnicode_CheckExact(v)) {
407 Py_INCREF(v);
408 return v;
409 }
410#endif
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000411 if (v->ob_type->tp_str == NULL)
412 return PyObject_Repr(v);
413
414 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000415 if (res == NULL)
416 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000417 type_ok = PyString_Check(res);
418#ifdef Py_USING_UNICODE
419 type_ok = type_ok || PyUnicode_Check(res);
420#endif
421 if (!type_ok) {
422 PyErr_Format(PyExc_TypeError,
423 "__str__ returned non-string (type %.200s)",
424 res->ob_type->tp_name);
425 Py_DECREF(res);
426 return NULL;
427 }
428 return res;
429}
430
431PyObject *
432PyObject_Str(PyObject *v)
433{
434 PyObject *res = _PyObject_Str(v);
435 if (res == NULL)
436 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000437#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000438 if (PyUnicode_Check(res)) {
439 PyObject* str;
440 str = PyUnicode_AsEncodedString(res, NULL, NULL);
441 Py_DECREF(res);
442 if (str)
443 res = str;
444 else
445 return NULL;
446 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000447#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +0000448 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000449 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000450}
451
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000452#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000453PyObject *
454PyObject_Unicode(PyObject *v)
455{
456 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000457 PyObject *func;
Neal Norwitz75801462006-03-14 06:02:16 +0000458 PyObject *str;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000459 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000460
Georg Brandl3daf7582006-03-13 22:22:11 +0000461 if (v == NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000462 res = PyString_FromString("<NULL>");
Neal Norwitz75801462006-03-14 06:02:16 +0000463 if (res == NULL)
464 return NULL;
465 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
466 Py_DECREF(res);
467 return str;
Georg Brandl3daf7582006-03-13 22:22:11 +0000468 } else if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000469 Py_INCREF(v);
470 return v;
471 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000472 /* XXX As soon as we have a tp_unicode slot, we should
473 check this before trying the __unicode__
474 method. */
475 if (unicodestr == NULL) {
476 unicodestr= PyString_InternFromString("__unicode__");
477 if (unicodestr == NULL)
478 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000479 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000480 func = PyObject_GetAttr(v, unicodestr);
481 if (func != NULL) {
482 res = PyEval_CallObject(func, (PyObject *)NULL);
483 Py_DECREF(func);
484 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000485 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000486 PyErr_Clear();
487 if (PyUnicode_Check(v)) {
488 /* For a Unicode subtype that's didn't overwrite __unicode__,
489 return a true Unicode object with the same data. */
490 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
491 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000492 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000493 if (PyString_CheckExact(v)) {
494 Py_INCREF(v);
495 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000496 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000497 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000498 if (v->ob_type->tp_str != NULL)
499 res = (*v->ob_type->tp_str)(v);
500 else
501 res = PyObject_Repr(v);
502 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000503 }
504 if (res == NULL)
505 return NULL;
506 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000507 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000508 Py_DECREF(res);
Neal Norwitz75801462006-03-14 06:02:16 +0000509 res = str;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000510 }
511 return res;
512}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000513#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000514
515
Guido van Rossuma4073002002-05-31 20:03:54 +0000516/* Helper to warn about deprecated tp_compare return values. Return:
517 -2 for an exception;
518 -1 if v < w;
519 0 if v == w;
520 1 if v > w.
521 (This function cannot return 2.)
522*/
523static int
524adjust_tp_compare(int c)
525{
526 if (PyErr_Occurred()) {
527 if (c != -1 && c != -2) {
528 PyObject *t, *v, *tb;
529 PyErr_Fetch(&t, &v, &tb);
530 if (PyErr_Warn(PyExc_RuntimeWarning,
531 "tp_compare didn't return -1 or -2 "
532 "for exception") < 0) {
533 Py_XDECREF(t);
534 Py_XDECREF(v);
535 Py_XDECREF(tb);
536 }
537 else
538 PyErr_Restore(t, v, tb);
539 }
540 return -2;
541 }
542 else if (c < -1 || c > 1) {
543 if (PyErr_Warn(PyExc_RuntimeWarning,
544 "tp_compare didn't return -1, 0 or 1") < 0)
545 return -2;
546 else
547 return c < -1 ? -1 : 1;
548 }
549 else {
550 assert(c >= -1 && c <= 1);
551 return c;
552 }
553}
554
555
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000556/* Macro to get the tp_richcompare field of a type if defined */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000557#define RICHCOMPARE(t) ((t)->tp_richcompare)
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000558
Guido van Rossume797ec12001-01-17 15:24:28 +0000559/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000560int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000561
Guido van Rossume797ec12001-01-17 15:24:28 +0000562/* Try a genuine rich comparison, returning an object. Return:
563 NULL for exception;
564 NotImplemented if this particular rich comparison is not implemented or
565 undefined;
566 some object not equal to NotImplemented if it is implemented
567 (this latter object may not be a Boolean).
568*/
569static PyObject *
570try_rich_compare(PyObject *v, PyObject *w, int op)
571{
572 richcmpfunc f;
573 PyObject *res;
574
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000575 if (v->ob_type != w->ob_type &&
576 PyType_IsSubtype(w->ob_type, v->ob_type) &&
577 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000578 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000579 if (res != Py_NotImplemented)
580 return res;
581 Py_DECREF(res);
582 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000583 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000584 res = (*f)(v, w, op);
585 if (res != Py_NotImplemented)
586 return res;
587 Py_DECREF(res);
588 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000589 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000590 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000591 }
592 res = Py_NotImplemented;
593 Py_INCREF(res);
594 return res;
595}
596
597/* Try a genuine rich comparison, returning an int. Return:
598 -1 for exception (including the case where try_rich_compare() returns an
599 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000600 0 if the outcome is false;
601 1 if the outcome is true;
602 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000603*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000604static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000605try_rich_compare_bool(PyObject *v, PyObject *w, int op)
606{
607 PyObject *res;
608 int ok;
609
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000610 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000611 return 2; /* Shortcut, avoid INCREF+DECREF */
612 res = try_rich_compare(v, w, op);
613 if (res == NULL)
614 return -1;
615 if (res == Py_NotImplemented) {
616 Py_DECREF(res);
617 return 2;
618 }
619 ok = PyObject_IsTrue(res);
620 Py_DECREF(res);
621 return ok;
622}
623
624/* Try rich comparisons to determine a 3-way comparison. Return:
625 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000626 -1 if v < w;
627 0 if v == w;
628 1 if v > w;
629 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000630*/
631static int
632try_rich_to_3way_compare(PyObject *v, PyObject *w)
633{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000634 static struct { int op; int outcome; } tries[3] = {
635 /* Try this operator, and if it is true, use this outcome: */
636 {Py_EQ, 0},
637 {Py_LT, -1},
638 {Py_GT, 1},
639 };
640 int i;
641
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000642 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000643 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000644
645 for (i = 0; i < 3; i++) {
646 switch (try_rich_compare_bool(v, w, tries[i].op)) {
647 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000648 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000649 case 1:
650 return tries[i].outcome;
651 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000652 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000653
654 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000655}
656
657/* Try a 3-way comparison, returning an int. Return:
658 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000659 -1 if v < w;
660 0 if v == w;
661 1 if v > w;
662 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000663*/
664static int
665try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000666{
667 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000668 cmpfunc f;
669
670 /* Comparisons involving instances are given to instance_compare,
671 which has the same return conventions as this function. */
672
Guido van Rossumab3b0342001-09-18 20:38:53 +0000673 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000674
Guido van Rossumab3b0342001-09-18 20:38:53 +0000675 /* If both have the same (non-NULL) tp_compare, use it. */
676 if (f != NULL && f == w->ob_type->tp_compare) {
677 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000678 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000679 }
680
681 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
682 if (f == _PyObject_SlotCompare ||
683 w->ob_type->tp_compare == _PyObject_SlotCompare)
684 return _PyObject_SlotCompare(v, w);
685
Armin Rigoa1748132004-12-23 22:13:13 +0000686 /* If we're here, v and w,
687 a) are not instances;
688 b) have different types or a type without tp_compare; and
689 c) don't have a user-defined tp_compare.
690 tp_compare implementations in C assume that both arguments
Neal Norwitz4886cc32006-08-21 17:06:07 +0000691 have their type, so we give up if the coercion fails.
Armin Rigoa1748132004-12-23 22:13:13 +0000692 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000693 c = PyNumber_CoerceEx(&v, &w);
694 if (c < 0)
695 return -2;
696 if (c > 0)
697 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000698 f = v->ob_type->tp_compare;
699 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000700 c = (*f)(v, w);
701 Py_DECREF(v);
702 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000703 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000704 }
705
Guido van Rossume797ec12001-01-17 15:24:28 +0000706 /* No comparison defined */
707 Py_DECREF(v);
708 Py_DECREF(w);
709 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000710}
711
Guido van Rossume797ec12001-01-17 15:24:28 +0000712/* Final fallback 3-way comparison, returning an int. Return:
713 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000714 -1 if v < w;
715 0 if v == w;
716 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000717*/
718static int
719default_3way_compare(PyObject *v, PyObject *w)
720{
721 int c;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000722 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000723
724 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000725 /* When comparing these pointers, they must be cast to
726 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
727 * uintptr_t). ANSI specifies that pointer compares other
728 * than == and != to non-related structures are undefined.
729 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000730 Py_uintptr_t vv = (Py_uintptr_t)v;
731 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000732 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
733 }
734
Guido van Rossum0871e932001-01-22 19:28:09 +0000735 /* None is smaller than anything */
736 if (v == Py_None)
737 return -1;
738 if (w == Py_None)
739 return 1;
740
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000741 /* different type: compare type names; numbers are smaller */
742 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000743 vname = "";
744 else
745 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000746 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000747 wname = "";
748 else
749 wname = w->ob_type->tp_name;
750 c = strcmp(vname, wname);
751 if (c < 0)
752 return -1;
753 if (c > 0)
754 return 1;
755 /* Same type name, or (more likely) incomparable numeric types */
756 return ((Py_uintptr_t)(v->ob_type) < (
757 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000758}
759
Tim Peters6d60b2e2001-05-07 20:53:51 +0000760/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000761 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000762 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000763 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000764 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000765 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000766 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000767*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000768static int
Fred Drake100814d2000-07-09 15:48:49 +0000769do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000770{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000771 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000772 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000773
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000774 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000775 && (f = v->ob_type->tp_compare) != NULL) {
776 c = (*f)(v, w);
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000777 return adjust_tp_compare(c);
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000778 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000779 /* We only get here if one of the following is true:
780 a) v and w have different types
781 b) v and w have the same type, which doesn't have tp_compare
782 c) v and w are instances, and either __cmp__ is not defined or
783 __cmp__ returns NotImplemented
784 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000785 c = try_rich_to_3way_compare(v, w);
786 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000787 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000788 c = try_3way_compare(v, w);
789 if (c < 2)
790 return c;
791 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000792}
793
Tim Petersc99213f2001-11-04 05:57:16 +0000794/* Compare v to w. Return
795 -1 if v < w or exception (PyErr_Occurred() true in latter case).
796 0 if v == w.
797 1 if v > w.
798 XXX The docs (C API manual) say the return value is undefined in case
799 XXX of error.
800*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801int
Fred Drake100814d2000-07-09 15:48:49 +0000802PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000803{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000804 int result;
805
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000806 if (v == NULL || w == NULL) {
807 PyErr_BadInternalCall();
808 return -1;
809 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000810 if (v == w)
811 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000812 if (Py_EnterRecursiveCall(" in cmp"))
813 return -1;
814 result = do_cmp(v, w);
815 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000816 return result < 0 ? -1 : result;
817}
818
Tim Petersc99213f2001-11-04 05:57:16 +0000819/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000820static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000821convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000822{
Guido van Rossume797ec12001-01-17 15:24:28 +0000823 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000824 switch (op) {
825 case Py_LT: c = c < 0; break;
826 case Py_LE: c = c <= 0; break;
827 case Py_EQ: c = c == 0; break;
828 case Py_NE: c = c != 0; break;
829 case Py_GT: c = c > 0; break;
830 case Py_GE: c = c >= 0; break;
831 }
832 result = c ? Py_True : Py_False;
833 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000834 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000835}
Tim Peters803526b2002-07-07 05:13:56 +0000836
Tim Petersc99213f2001-11-04 05:57:16 +0000837/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
838 Return
839 NULL if error
840 Py_True if v op w
841 Py_False if not (v op w)
842*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000843static PyObject *
844try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
845{
846 int c;
847
848 c = try_3way_compare(v, w);
849 if (c >= 2)
850 c = default_3way_compare(v, w);
851 if (c <= -2)
852 return NULL;
853 return convert_3way_to_object(op, c);
854}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000855
Tim Petersc99213f2001-11-04 05:57:16 +0000856/* Do rich comparison on v and w. Return
857 NULL if error
858 Else a new reference to an object other than Py_NotImplemented, usually(?):
859 Py_True if v op w
860 Py_False if not (v op w)
861*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000862static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000863do_richcmp(PyObject *v, PyObject *w, int op)
864{
865 PyObject *res;
866
867 res = try_rich_compare(v, w, op);
868 if (res != Py_NotImplemented)
869 return res;
870 Py_DECREF(res);
871
872 return try_3way_to_rich_compare(v, w, op);
873}
874
Tim Petersc99213f2001-11-04 05:57:16 +0000875/* Return:
876 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000877 some object not equal to NotImplemented if it is implemented
878 (this latter object may not be a Boolean).
879*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000880PyObject *
881PyObject_RichCompare(PyObject *v, PyObject *w, int op)
882{
883 PyObject *res;
884
885 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000886 if (Py_EnterRecursiveCall(" in cmp"))
887 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000888
Armin Rigo2b3eb402003-10-28 12:05:48 +0000889 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000890 get out cheap (don't bother with coercions etc.). */
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000891 if (v->ob_type == w->ob_type) {
Tim Peters67754e92001-11-04 07:29:31 +0000892 cmpfunc fcmp;
893 richcmpfunc frich = RICHCOMPARE(v->ob_type);
894 /* If the type has richcmp, try it first. try_rich_compare
895 tries it two-sided, which is not needed since we've a
896 single type only. */
897 if (frich != NULL) {
898 res = (*frich)(v, w, op);
899 if (res != Py_NotImplemented)
900 goto Done;
901 Py_DECREF(res);
902 }
903 /* No richcmp, or this particular richmp not implemented.
904 Try 3-way cmp. */
905 fcmp = v->ob_type->tp_compare;
906 if (fcmp != NULL) {
907 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000908 c = adjust_tp_compare(c);
909 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000910 res = NULL;
911 goto Done;
912 }
913 res = convert_3way_to_object(op, c);
914 goto Done;
915 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000916 }
Tim Peters67754e92001-11-04 07:29:31 +0000917
918 /* Fast path not taken, or couldn't deliver a useful result. */
919 res = do_richcmp(v, w, op);
920Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000921 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000922 return res;
923}
924
Tim Petersde9725f2001-05-05 10:06:17 +0000925/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000926int
927PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
928{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000929 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000930 int ok;
931
Raymond Hettinger93d44812004-03-21 17:01:44 +0000932 /* Quick result when objects are the same.
933 Guarantees that identity implies equality. */
934 if (v == w) {
935 if (op == Py_EQ)
936 return 1;
937 else if (op == Py_NE)
938 return 0;
939 }
940
941 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000942 if (res == NULL)
943 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000944 if (PyBool_Check(res))
945 ok = (res == Py_True);
946 else
947 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000948 Py_DECREF(res);
949 return ok;
950}
Fred Drake13634cf2000-06-29 19:17:04 +0000951
952/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000953 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000954
955 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
956*/
957
958long
Fred Drake100814d2000-07-09 15:48:49 +0000959_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000960{
Tim Peters39dce292000-08-15 03:34:48 +0000961 double intpart, fractpart;
962 int expo;
963 long hipart;
964 long x; /* the final hash value */
965 /* This is designed so that Python numbers of different types
966 * that compare equal hash to the same value; otherwise comparisons
967 * of mapping keys will turn out weird.
968 */
969
Tim Peters39dce292000-08-15 03:34:48 +0000970 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000971 if (fractpart == 0.0) {
972 /* This must return the same hash as an equal int or long. */
973 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
974 /* Convert to long and use its hash. */
975 PyObject *plong; /* converted to Python long */
976 if (Py_IS_INFINITY(intpart))
977 /* can't convert to long int -- arbitrary */
978 v = v < 0 ? -271828.0 : 314159.0;
979 plong = PyLong_FromDouble(v);
980 if (plong == NULL)
981 return -1;
982 x = PyObject_Hash(plong);
983 Py_DECREF(plong);
984 return x;
985 }
986 /* Fits in a C long == a Python int, so is its own hash. */
987 x = (long)intpart;
988 if (x == -1)
989 x = -2;
990 return x;
991 }
992 /* The fractional part is non-zero, so we don't have to worry about
993 * making this match the hash of some other type.
994 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000995 * Since the VAX D double format has 56 mantissa bits, which is the
996 * most of any double format in use, each of these parts may have as
997 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000998 * So, assuming sizeof(long) >= 4, each part can be broken into two
999 * longs; frexp and multiplication are used to do that.
1000 * Also, since the Cray double format has 15 exponent bits, which is
1001 * the most of any double format in use, shifting the exponent field
1002 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001003 */
Tim Peters39dce292000-08-15 03:34:48 +00001004 v = frexp(v, &expo);
1005 v *= 2147483648.0; /* 2**31 */
1006 hipart = (long)v; /* take the top 32 bits */
1007 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1008 x = hipart + (long)v + (expo << 15);
1009 if (x == -1)
1010 x = -2;
1011 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001012}
1013
1014long
Fred Drake100814d2000-07-09 15:48:49 +00001015_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001016{
1017#if SIZEOF_LONG >= SIZEOF_VOID_P
1018 return (long)p;
1019#else
1020 /* convert to a Python long and hash that */
1021 PyObject* longobj;
1022 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001023
Fred Drake13634cf2000-06-29 19:17:04 +00001024 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1025 x = -1;
1026 goto finally;
1027 }
1028 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001029
Fred Drake13634cf2000-06-29 19:17:04 +00001030finally:
1031 Py_XDECREF(longobj);
1032 return x;
1033#endif
1034}
1035
1036
Guido van Rossum9bfef441993-03-29 10:43:31 +00001037long
Fred Drake100814d2000-07-09 15:48:49 +00001038PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001039{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001040 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001041 if (tp->tp_hash != NULL)
1042 return (*tp->tp_hash)(v);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001043 /* Otherwise, the object can't be hashed */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001044 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1045 v->ob_type->tp_name);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001046 return -1;
1047}
1048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001049PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001050PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001051{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001053
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054 if (v->ob_type->tp_getattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001055 return (*v->ob_type->tp_getattr)(v, (char*)name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056 w = PyString_InternFromString(name);
1057 if (w == NULL)
1058 return NULL;
1059 res = PyObject_GetAttr(v, w);
1060 Py_XDECREF(w);
1061 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001062}
1063
1064int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001065PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001066{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001067 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001068 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001069 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001070 return 1;
1071 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001072 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001073 return 0;
1074}
1075
1076int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001077PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001078{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001079 PyObject *s;
1080 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001081
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082 if (v->ob_type->tp_setattr != NULL)
Martin v. Löwis15e62742006-02-27 16:46:16 +00001083 return (*v->ob_type->tp_setattr)(v, (char*)name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084 s = PyString_InternFromString(name);
1085 if (s == NULL)
1086 return -1;
1087 res = PyObject_SetAttr(v, s, w);
1088 Py_XDECREF(s);
1089 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001090}
1091
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001092PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001093PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001094{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001095 PyTypeObject *tp = v->ob_type;
1096
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001097 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001098#ifdef Py_USING_UNICODE
1099 /* The Unicode to string conversion is done here because the
1100 existing tp_getattro slots expect a string object as name
1101 and we wouldn't want to break those. */
1102 if (PyUnicode_Check(name)) {
1103 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1104 if (name == NULL)
1105 return NULL;
1106 }
1107 else
1108#endif
1109 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001110 PyErr_Format(PyExc_TypeError,
1111 "attribute name must be string, not '%.200s'",
1112 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001113 return NULL;
1114 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001115 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 if (tp->tp_getattro != NULL)
1117 return (*tp->tp_getattro)(v, name);
1118 if (tp->tp_getattr != NULL)
1119 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1120 PyErr_Format(PyExc_AttributeError,
1121 "'%.50s' object has no attribute '%.400s'",
1122 tp->tp_name, PyString_AS_STRING(name));
1123 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001124}
1125
1126int
Fred Drake100814d2000-07-09 15:48:49 +00001127PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001128{
1129 PyObject *res = PyObject_GetAttr(v, name);
1130 if (res != NULL) {
1131 Py_DECREF(res);
1132 return 1;
1133 }
1134 PyErr_Clear();
1135 return 0;
1136}
1137
1138int
Fred Drake100814d2000-07-09 15:48:49 +00001139PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001140{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001142 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001143
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001144 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001145#ifdef Py_USING_UNICODE
1146 /* The Unicode to string conversion is done here because the
1147 existing tp_setattro slots expect a string object as name
1148 and we wouldn't want to break those. */
1149 if (PyUnicode_Check(name)) {
1150 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1151 if (name == NULL)
1152 return -1;
1153 }
Tim Peters803526b2002-07-07 05:13:56 +00001154 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001155#endif
1156 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001157 PyErr_Format(PyExc_TypeError,
1158 "attribute name must be string, not '%.200s'",
1159 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001160 return -1;
1161 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001162 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001163 else
1164 Py_INCREF(name);
1165
1166 PyString_InternInPlace(&name);
1167 if (tp->tp_setattro != NULL) {
1168 err = (*tp->tp_setattro)(v, name, value);
1169 Py_DECREF(name);
1170 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001171 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001172 if (tp->tp_setattr != NULL) {
1173 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1174 Py_DECREF(name);
1175 return err;
1176 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001177 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1179 PyErr_Format(PyExc_TypeError,
1180 "'%.100s' object has no attributes "
1181 "(%s .%.100s)",
1182 tp->tp_name,
1183 value==NULL ? "del" : "assign to",
1184 PyString_AS_STRING(name));
1185 else
1186 PyErr_Format(PyExc_TypeError,
1187 "'%.100s' object has only read-only attributes "
1188 "(%s .%.100s)",
1189 tp->tp_name,
1190 value==NULL ? "del" : "assign to",
1191 PyString_AS_STRING(name));
1192 return -1;
1193}
1194
1195/* Helper to get a pointer to an object's __dict__ slot, if any */
1196
1197PyObject **
1198_PyObject_GetDictPtr(PyObject *obj)
1199{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001200 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 PyTypeObject *tp = obj->ob_type;
1202
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203 dictoffset = tp->tp_dictoffset;
1204 if (dictoffset == 0)
1205 return NULL;
1206 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001207 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001208 size_t size;
1209
1210 tsize = ((PyVarObject *)obj)->ob_size;
1211 if (tsize < 0)
1212 tsize = -tsize;
1213 size = _PyObject_VAR_SIZE(tp, tsize);
1214
Tim Peters6d483d32001-10-06 21:27:34 +00001215 dictoffset += (long)size;
1216 assert(dictoffset > 0);
1217 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218 }
1219 return (PyObject **) ((char *)obj + dictoffset);
1220}
1221
Tim Peters6d6c1a32001-08-02 04:15:00 +00001222PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001223PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001224{
1225 Py_INCREF(obj);
1226 return obj;
1227}
1228
Michael W. Hudson1593f502004-09-14 17:09:47 +00001229/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1230
Raymond Hettinger01538262003-03-17 08:24:35 +00001231PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1233{
1234 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001235 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001236 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 descrgetfunc f;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001238 Py_ssize_t dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001239 PyObject **dictptr;
1240
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001241 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001242#ifdef Py_USING_UNICODE
1243 /* The Unicode to string conversion is done here because the
1244 existing tp_setattro slots expect a string object as name
1245 and we wouldn't want to break those. */
1246 if (PyUnicode_Check(name)) {
1247 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1248 if (name == NULL)
1249 return NULL;
1250 }
Tim Peters803526b2002-07-07 05:13:56 +00001251 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001252#endif
1253 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001254 PyErr_Format(PyExc_TypeError,
1255 "attribute name must be string, not '%.200s'",
1256 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001257 return NULL;
1258 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001259 }
1260 else
1261 Py_INCREF(name);
1262
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001264 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001265 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266 }
1267
Guido van Rossum056fbf42002-08-19 19:22:50 +00001268 /* Inline _PyType_Lookup */
1269 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001271 PyObject *mro, *base, *dict;
1272
1273 /* Look in tp_dict of types in MRO */
1274 mro = tp->tp_mro;
1275 assert(mro != NULL);
1276 assert(PyTuple_Check(mro));
1277 n = PyTuple_GET_SIZE(mro);
1278 for (i = 0; i < n; i++) {
1279 base = PyTuple_GET_ITEM(mro, i);
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001280 assert(PyType_Check(base));
1281 dict = ((PyTypeObject *)base)->tp_dict;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001282 assert(dict && PyDict_Check(dict));
1283 descr = PyDict_GetItem(dict, name);
1284 if (descr != NULL)
1285 break;
1286 }
1287 }
1288
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001289 Py_XINCREF(descr);
1290
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001292 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001294 if (f != NULL && PyDescr_IsData(descr)) {
1295 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001296 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001297 goto done;
1298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 }
1300
Guido van Rossumc66ff442002-08-19 16:50:48 +00001301 /* Inline _PyObject_GetDictPtr */
1302 dictoffset = tp->tp_dictoffset;
1303 if (dictoffset != 0) {
1304 PyObject *dict;
1305 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001306 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001307 size_t size;
1308
1309 tsize = ((PyVarObject *)obj)->ob_size;
1310 if (tsize < 0)
1311 tsize = -tsize;
1312 size = _PyObject_VAR_SIZE(tp, tsize);
1313
1314 dictoffset += (long)size;
1315 assert(dictoffset > 0);
1316 assert(dictoffset % SIZEOF_VOID_P == 0);
1317 }
1318 dictptr = (PyObject **) ((char *)obj + dictoffset);
1319 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001321 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 if (res != NULL) {
1323 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001324 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001325 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 }
1327 }
1328 }
1329
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001330 if (f != NULL) {
1331 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001332 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001333 goto done;
1334 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335
1336 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001337 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001338 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001339 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 }
1341
1342 PyErr_Format(PyExc_AttributeError,
1343 "'%.50s' object has no attribute '%.400s'",
1344 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001345 done:
1346 Py_DECREF(name);
1347 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001348}
1349
1350int
1351PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1352{
1353 PyTypeObject *tp = obj->ob_type;
1354 PyObject *descr;
1355 descrsetfunc f;
1356 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001357 int res = -1;
1358
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001360#ifdef Py_USING_UNICODE
1361 /* The Unicode to string conversion is done here because the
1362 existing tp_setattro slots expect a string object as name
1363 and we wouldn't want to break those. */
1364 if (PyUnicode_Check(name)) {
1365 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1366 if (name == NULL)
1367 return -1;
1368 }
Tim Peters803526b2002-07-07 05:13:56 +00001369 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001370#endif
1371 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001372 PyErr_Format(PyExc_TypeError,
1373 "attribute name must be string, not '%.200s'",
1374 name->ob_type->tp_name);
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001375 return -1;
1376 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001377 }
1378 else
1379 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380
1381 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001382 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001383 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384 }
1385
1386 descr = _PyType_Lookup(tp, name);
1387 f = NULL;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001388 if (descr != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001389 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001390 if (f != NULL && PyDescr_IsData(descr)) {
1391 res = f(descr, obj, value);
1392 goto done;
1393 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 }
1395
1396 dictptr = _PyObject_GetDictPtr(obj);
1397 if (dictptr != NULL) {
1398 PyObject *dict = *dictptr;
1399 if (dict == NULL && value != NULL) {
1400 dict = PyDict_New();
1401 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001402 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403 *dictptr = dict;
1404 }
1405 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406 if (value == NULL)
1407 res = PyDict_DelItem(dict, name);
1408 else
1409 res = PyDict_SetItem(dict, name, value);
1410 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1411 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001412 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001413 }
1414 }
1415
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001416 if (f != NULL) {
1417 res = f(descr, obj, value);
1418 goto done;
1419 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420
1421 if (descr == NULL) {
1422 PyErr_Format(PyExc_AttributeError,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001423 "'%.100s' object has no attribute '%.200s'",
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001425 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001426 }
1427
1428 PyErr_Format(PyExc_AttributeError,
1429 "'%.50s' object attribute '%.400s' is read-only",
1430 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001431 done:
1432 Py_DECREF(name);
1433 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001434}
1435
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001436/* Test a value used as condition, e.g., in a for or if statement.
1437 Return -1 if an error occurred */
1438
1439int
Fred Drake100814d2000-07-09 15:48:49 +00001440PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001441{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001442 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001443 if (v == Py_True)
1444 return 1;
1445 if (v == Py_False)
1446 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001447 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001448 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001449 else if (v->ob_type->tp_as_number != NULL &&
1450 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001451 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001452 else if (v->ob_type->tp_as_mapping != NULL &&
1453 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001454 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001455 else if (v->ob_type->tp_as_sequence != NULL &&
1456 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001457 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1458 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001459 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001460 /* if it is negative, it should be either -1 or -2 */
1461 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001462}
1463
Tim Peters803526b2002-07-07 05:13:56 +00001464/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001465 Return -1 if an error occurred */
1466
1467int
Fred Drake100814d2000-07-09 15:48:49 +00001468PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001469{
1470 int res;
1471 res = PyObject_IsTrue(v);
1472 if (res < 0)
1473 return res;
1474 return res == 0;
1475}
1476
Guido van Rossum5524a591995-01-10 15:26:20 +00001477/* Coerce two numeric types to the "larger" one.
1478 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001479 Return value:
1480 -1 if an error occurred;
1481 0 if the coercion succeeded (and then the reference counts are increased);
1482 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001483*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001484int
Fred Drake100814d2000-07-09 15:48:49 +00001485PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001486{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001487 register PyObject *v = *pv;
1488 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001489 int res;
1490
Guido van Rossum5524a591995-01-10 15:26:20 +00001491 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1492 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1493 if (res <= 0)
1494 return res;
1495 }
1496 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1497 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1498 if (res <= 0)
1499 return res;
1500 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001501 return 1;
1502}
1503
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001504/* Test whether an object can be called */
1505
1506int
Fred Drake100814d2000-07-09 15:48:49 +00001507PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001508{
1509 if (x == NULL)
1510 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001511 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001512}
1513
Tim Peters7eea37e2001-09-04 22:08:56 +00001514/* Helper for PyObject_Dir.
1515 Merge the __dict__ of aclass into dict, and recursively also all
1516 the __dict__s of aclass's base classes. The order of merging isn't
1517 defined, as it's expected that only the final set of dict keys is
1518 interesting.
1519 Return 0 on success, -1 on error.
1520*/
1521
1522static int
1523merge_class_dict(PyObject* dict, PyObject* aclass)
1524{
1525 PyObject *classdict;
1526 PyObject *bases;
1527
1528 assert(PyDict_Check(dict));
1529 assert(aclass);
1530
1531 /* Merge in the type's dict (if any). */
1532 classdict = PyObject_GetAttrString(aclass, "__dict__");
1533 if (classdict == NULL)
1534 PyErr_Clear();
1535 else {
1536 int status = PyDict_Update(dict, classdict);
1537 Py_DECREF(classdict);
1538 if (status < 0)
1539 return -1;
1540 }
1541
1542 /* Recursively merge in the base types' (if any) dicts. */
1543 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001544 if (bases == NULL)
1545 PyErr_Clear();
1546 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001547 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001548 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001549 n = PySequence_Size(bases); /* This better be right */
1550 if (n < 0)
1551 PyErr_Clear();
1552 else {
1553 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001554 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001555 PyObject *base = PySequence_GetItem(bases, i);
1556 if (base == NULL) {
1557 Py_DECREF(bases);
1558 return -1;
1559 }
Tim Peters18e70832003-02-05 19:35:19 +00001560 status = merge_class_dict(dict, base);
1561 Py_DECREF(base);
1562 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001563 Py_DECREF(bases);
1564 return -1;
1565 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001566 }
1567 }
1568 Py_DECREF(bases);
1569 }
1570 return 0;
1571}
1572
Tim Peters305b5852001-09-17 02:38:46 +00001573/* Helper for PyObject_Dir.
1574 If obj has an attr named attrname that's a list, merge its string
1575 elements into keys of dict.
1576 Return 0 on success, -1 on error. Errors due to not finding the attr,
1577 or the attr not being a list, are suppressed.
1578*/
1579
1580static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001581merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001582{
1583 PyObject *list;
1584 int result = 0;
1585
1586 assert(PyDict_Check(dict));
1587 assert(obj);
1588 assert(attrname);
1589
1590 list = PyObject_GetAttrString(obj, attrname);
1591 if (list == NULL)
1592 PyErr_Clear();
1593
1594 else if (PyList_Check(list)) {
1595 int i;
1596 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1597 PyObject *item = PyList_GET_ITEM(list, i);
1598 if (PyString_Check(item)) {
1599 result = PyDict_SetItem(dict, item, Py_None);
1600 if (result < 0)
1601 break;
1602 }
1603 }
1604 }
1605
1606 Py_XDECREF(list);
1607 return result;
1608}
1609
Tim Peters7eea37e2001-09-04 22:08:56 +00001610/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1611 docstring, which should be kept in synch with this implementation. */
1612
1613PyObject *
1614PyObject_Dir(PyObject *arg)
1615{
1616 /* Set exactly one of these non-NULL before the end. */
1617 PyObject *result = NULL; /* result list */
1618 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1619
1620 /* If NULL arg, return the locals. */
1621 if (arg == NULL) {
1622 PyObject *locals = PyEval_GetLocals();
1623 if (locals == NULL)
1624 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001625 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001626 if (result == NULL)
1627 goto error;
1628 }
1629
1630 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001631 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001632 masterdict = PyObject_GetAttrString(arg, "__dict__");
1633 if (masterdict == NULL)
1634 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001635 if (!PyDict_Check(masterdict)) {
1636 PyErr_SetString(PyExc_TypeError,
1637 "module.__dict__ is not a dictionary");
1638 goto error;
1639 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001640 }
1641
1642 /* Elif some form of type or class, grab its dict and its bases.
1643 We deliberately don't suck up its __class__, as methods belonging
1644 to the metaclass would probably be more confusing than helpful. */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001645 else if (PyType_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001646 masterdict = PyDict_New();
1647 if (masterdict == NULL)
1648 goto error;
1649 if (merge_class_dict(masterdict, arg) < 0)
1650 goto error;
1651 }
1652
1653 /* Else look at its dict, and the attrs reachable from its class. */
1654 else {
1655 PyObject *itsclass;
1656 /* Create a dict to start with. CAUTION: Not everything
1657 responding to __dict__ returns a dict! */
1658 masterdict = PyObject_GetAttrString(arg, "__dict__");
1659 if (masterdict == NULL) {
1660 PyErr_Clear();
1661 masterdict = PyDict_New();
1662 }
1663 else if (!PyDict_Check(masterdict)) {
1664 Py_DECREF(masterdict);
1665 masterdict = PyDict_New();
1666 }
1667 else {
1668 /* The object may have returned a reference to its
1669 dict, so copy it to avoid mutating it. */
1670 PyObject *temp = PyDict_Copy(masterdict);
1671 Py_DECREF(masterdict);
1672 masterdict = temp;
1673 }
1674 if (masterdict == NULL)
1675 goto error;
1676
Tim Peters305b5852001-09-17 02:38:46 +00001677 /* Merge in __members__ and __methods__ (if any).
1678 XXX Would like this to go away someday; for now, it's
1679 XXX needed to get at im_self etc of method objects. */
1680 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1681 goto error;
1682 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1683 goto error;
1684
Tim Peters7eea37e2001-09-04 22:08:56 +00001685 /* Merge in attrs reachable from its class.
1686 CAUTION: Not all objects have a __class__ attr. */
1687 itsclass = PyObject_GetAttrString(arg, "__class__");
1688 if (itsclass == NULL)
1689 PyErr_Clear();
1690 else {
1691 int status = merge_class_dict(masterdict, itsclass);
1692 Py_DECREF(itsclass);
1693 if (status < 0)
1694 goto error;
1695 }
1696 }
1697
1698 assert((result == NULL) ^ (masterdict == NULL));
1699 if (masterdict != NULL) {
1700 /* The result comes from its keys. */
1701 assert(result == NULL);
1702 result = PyDict_Keys(masterdict);
1703 if (result == NULL)
1704 goto error;
1705 }
1706
1707 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001708 if (!PyList_Check(result)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001709 PyErr_Format(PyExc_TypeError,
1710 "Expected keys() to be a list, not '%.200s'",
1711 result->ob_type->tp_name);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001712 goto error;
1713 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001714 if (PyList_Sort(result) != 0)
1715 goto error;
1716 else
1717 goto normal_return;
1718
1719 error:
1720 Py_XDECREF(result);
1721 result = NULL;
1722 /* fall through */
1723 normal_return:
1724 Py_XDECREF(masterdict);
1725 return result;
1726}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001727
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001728/*
1729NoObject is usable as a non-NULL undefined value, used by the macro None.
1730There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001731so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001732(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001733*/
1734
Guido van Rossum0c182a11992-03-27 17:26:13 +00001735/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001736static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001737none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001738{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001739 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740}
1741
Barry Warsaw9bf16442001-01-23 16:24:35 +00001742/* ARGUSED */
1743static void
Tim Peters803526b2002-07-07 05:13:56 +00001744none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001745{
1746 /* This should never get called, but we also don't want to SEGV if
1747 * we accidently decref None out of existance.
1748 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001749 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001750}
1751
1752
Guido van Rossumba21a492001-08-16 08:17:26 +00001753static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001754 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001755 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001756 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001757 0,
1758 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001759 none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001760 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001761 0, /*tp_getattr*/
1762 0, /*tp_setattr*/
1763 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001764 none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001765 0, /*tp_as_number*/
1766 0, /*tp_as_sequence*/
1767 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001768 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001769};
1770
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001771PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001772 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001773};
1774
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001775/* NotImplemented is an object that can be used to signal that an
1776 operation is not implemented for the given type combination. */
1777
1778static PyObject *
1779NotImplemented_repr(PyObject *op)
1780{
1781 return PyString_FromString("NotImplemented");
1782}
1783
1784static PyTypeObject PyNotImplemented_Type = {
1785 PyObject_HEAD_INIT(&PyType_Type)
1786 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001787 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001788 0,
1789 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001790 none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001791 0, /*tp_print*/
1792 0, /*tp_getattr*/
1793 0, /*tp_setattr*/
1794 0, /*tp_compare*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001795 NotImplemented_repr, /*tp_repr*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001796 0, /*tp_as_number*/
1797 0, /*tp_as_sequence*/
1798 0, /*tp_as_mapping*/
1799 0, /*tp_hash */
1800};
1801
1802PyObject _Py_NotImplementedStruct = {
1803 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1804};
1805
Guido van Rossumba21a492001-08-16 08:17:26 +00001806void
1807_Py_ReadyTypes(void)
1808{
1809 if (PyType_Ready(&PyType_Type) < 0)
1810 Py_FatalError("Can't initialize 'type'");
1811
Fred Drake0a4dd392004-07-02 18:57:45 +00001812 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1813 Py_FatalError("Can't initialize 'weakref'");
1814
Guido van Rossum77f6a652002-04-03 22:41:51 +00001815 if (PyType_Ready(&PyBool_Type) < 0)
1816 Py_FatalError("Can't initialize 'bool'");
1817
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001818 if (PyType_Ready(&PyBytes_Type) < 0)
1819 Py_FatalError("Can't initialize 'bytes'");
1820
Guido van Rossumcacfc072002-05-24 19:01:59 +00001821 if (PyType_Ready(&PyString_Type) < 0)
1822 Py_FatalError("Can't initialize 'str'");
1823
Guido van Rossumba21a492001-08-16 08:17:26 +00001824 if (PyType_Ready(&PyList_Type) < 0)
1825 Py_FatalError("Can't initialize 'list'");
1826
1827 if (PyType_Ready(&PyNone_Type) < 0)
1828 Py_FatalError("Can't initialize type(None)");
1829
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001830 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1831 Py_FatalError("Can't initialize type(Ellipsis)");
1832
Guido van Rossumba21a492001-08-16 08:17:26 +00001833 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1834 Py_FatalError("Can't initialize type(NotImplemented)");
1835}
1836
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001837
Guido van Rossum84a90321996-05-22 16:34:47 +00001838#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001839
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001840void
Fred Drake100814d2000-07-09 15:48:49 +00001841_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842{
Tim Peters34592512002-07-11 06:23:50 +00001843 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001845 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001846 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847}
1848
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001849void
Fred Drake100814d2000-07-09 15:48:49 +00001850_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001852#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001853 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001854#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001855 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001856 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001857 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001858 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001859 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001860#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001861 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1862 if (p == op)
1863 break;
1864 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001865 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001866 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001867#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001868 op->_ob_next->_ob_prev = op->_ob_prev;
1869 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001870 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001871 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001872}
1873
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001874void
Fred Drake100814d2000-07-09 15:48:49 +00001875_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001876{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001877 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001878 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001879 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880}
1881
Tim Peters269b2a62003-04-17 19:52:29 +00001882/* Print all live objects. Because PyObject_Print is called, the
1883 * interpreter must be in a healthy state.
1884 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001885void
Fred Drake100814d2000-07-09 15:48:49 +00001886_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001887{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001888 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001889 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001890 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001891 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001892 if (PyObject_Print(op, fp, 0) != 0)
1893 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001894 putc('\n', fp);
1895 }
1896}
1897
Tim Peters269b2a62003-04-17 19:52:29 +00001898/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1899 * doesn't make any calls to the Python C API, so is always safe to call.
1900 */
1901void
1902_Py_PrintReferenceAddresses(FILE *fp)
1903{
1904 PyObject *op;
1905 fprintf(fp, "Remaining object addresses:\n");
1906 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001907 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1908 op->ob_refcnt, op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001909}
1910
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001911PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001912_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001913{
1914 int i, n;
1915 PyObject *t = NULL;
1916 PyObject *res, *op;
1917
1918 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1919 return NULL;
1920 op = refchain._ob_next;
1921 res = PyList_New(0);
1922 if (res == NULL)
1923 return NULL;
1924 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1925 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001926 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001927 op = op->_ob_next;
1928 if (op == &refchain)
1929 return res;
1930 }
1931 if (PyList_Append(res, op) < 0) {
1932 Py_DECREF(res);
1933 return NULL;
1934 }
1935 op = op->_ob_next;
1936 }
1937 return res;
1938}
1939
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001940#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001941
1942
1943/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001944PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001945
1946
1947/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001948Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001949
1950
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001951/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001952
Thomas Wouters334fb892000-07-25 12:56:38 +00001953void *
Fred Drake100814d2000-07-09 15:48:49 +00001954PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001955{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001956 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001957}
1958
Thomas Wouters334fb892000-07-25 12:56:38 +00001959void *
1960PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001961{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001962 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001963}
1964
1965void
Thomas Wouters334fb892000-07-25 12:56:38 +00001966PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001967{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001968 PyMem_FREE(p);
1969}
1970
1971
Guido van Rossum86610361998-04-10 22:32:46 +00001972/* These methods are used to control infinite recursion in repr, str, print,
1973 etc. Container objects that may recursively contain themselves,
1974 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1975 Py_ReprLeave() to avoid infinite recursion.
1976
1977 Py_ReprEnter() returns 0 the first time it is called for a particular
1978 object and 1 every time thereafter. It returns -1 if an exception
1979 occurred. Py_ReprLeave() has no return value.
1980
1981 See dictobject.c and listobject.c for examples of use.
1982*/
1983
1984#define KEY "Py_Repr"
1985
1986int
Fred Drake100814d2000-07-09 15:48:49 +00001987Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001988{
1989 PyObject *dict;
1990 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001991 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001992
1993 dict = PyThreadState_GetDict();
1994 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001995 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001996 list = PyDict_GetItemString(dict, KEY);
1997 if (list == NULL) {
1998 list = PyList_New(0);
1999 if (list == NULL)
2000 return -1;
2001 if (PyDict_SetItemString(dict, KEY, list) < 0)
2002 return -1;
2003 Py_DECREF(list);
2004 }
2005 i = PyList_GET_SIZE(list);
2006 while (--i >= 0) {
2007 if (PyList_GET_ITEM(list, i) == obj)
2008 return 1;
2009 }
2010 PyList_Append(list, obj);
2011 return 0;
2012}
2013
2014void
Fred Drake100814d2000-07-09 15:48:49 +00002015Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002016{
2017 PyObject *dict;
2018 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002019 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002020
2021 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002022 if (dict == NULL)
2023 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002024 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002025 if (list == NULL || !PyList_Check(list))
2026 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002027 i = PyList_GET_SIZE(list);
2028 /* Count backwards because we always expect obj to be list[-1] */
2029 while (--i >= 0) {
2030 if (PyList_GET_ITEM(list, i) == obj) {
2031 PyList_SetSlice(list, i, i + 1, NULL);
2032 break;
2033 }
2034 }
2035}
Guido van Rossumd724b232000-03-13 16:01:29 +00002036
Tim Peters803526b2002-07-07 05:13:56 +00002037/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002038
Tim Peters803526b2002-07-07 05:13:56 +00002039/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002040int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002041
Tim Peters803526b2002-07-07 05:13:56 +00002042/* List of objects that still need to be cleaned up, singly linked via their
2043 * gc headers' gc_prev pointers.
2044 */
2045PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002046
Tim Peters803526b2002-07-07 05:13:56 +00002047/* Add op to the _PyTrash_delete_later list. Called when the current
2048 * call-stack depth gets large. op must be a currently untracked gc'ed
2049 * object, with refcount 0. Py_DECREF must already have been called on it.
2050 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002051void
Fred Drake100814d2000-07-09 15:48:49 +00002052_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002053{
Tim Peters803526b2002-07-07 05:13:56 +00002054 assert(PyObject_IS_GC(op));
2055 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2056 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002057 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002058 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002059}
2060
Tim Peters803526b2002-07-07 05:13:56 +00002061/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2062 * the call-stack unwinds again.
2063 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002064void
Fred Drake100814d2000-07-09 15:48:49 +00002065_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002066{
2067 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002068 PyObject *op = _PyTrash_delete_later;
2069 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002070
Neil Schemenauerf589c052002-03-29 03:05:54 +00002071 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002072 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002073
Tim Peters803526b2002-07-07 05:13:56 +00002074 /* Call the deallocator directly. This used to try to
2075 * fool Py_DECREF into calling it indirectly, but
2076 * Py_DECREF was already called on this object, and in
2077 * assorted non-release builds calling Py_DECREF again ends
2078 * up distorting allocation statistics.
2079 */
2080 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002081 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002082 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002083 --_PyTrash_delete_nesting;
2084 }
2085}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002086
2087#ifdef __cplusplus
2088}
2089#endif
2090