blob: 2a1f45a9e0d1ad7e1c17bff31327df609a3bcbbe [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 Rossum85a5fbb1990-10-14 12:07:46 +00005
Tim Peters34592512002-07-11 06:23:50 +00006#ifdef Py_REF_DEBUG
Mark Hammonda2905272002-07-29 13:42:14 +00007long _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Mark Hammonda2905272002-07-29 13:42:14 +000010int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000011
Guido van Rossum3f5da241990-12-20 15:06:42 +000012/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
13 These are used by the individual routines for object creation.
14 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015
Tim Peters78be7992003-03-23 02:51:01 +000016#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000017/* Head of circular doubly-linked list of all objects. These are linked
18 * together via the _ob_prev and _ob_next members of a PyObject, which
19 * exist only in a Py_TRACE_REFS build.
20 */
Tim Peters78be7992003-03-23 02:51:01 +000021static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000022
Tim Peters7571a0f2003-03-23 17:52:28 +000023/* Insert op at the front of the list of all objects. If force is true,
24 * op is added even if _ob_prev and _ob_next are non-NULL already. If
25 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
26 * force should be true if and only if op points to freshly allocated,
27 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000028 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000029 * Note that objects are normally added to the list via _Py_NewReference,
30 * which is called by PyObject_Init. Not all objects are initialized that
31 * way, though; exceptions include statically allocated type objects, and
32 * statically allocated singletons (like Py_True and Py_None).
33 */
Tim Peters36eb4df2003-03-23 03:33:13 +000034void
Tim Peters7571a0f2003-03-23 17:52:28 +000035_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000036{
Tim Peters7571a0f2003-03-23 17:52:28 +000037#ifdef Py_DEBUG
38 if (!force) {
39 /* If it's initialized memory, op must be in or out of
40 * the list unambiguously.
41 */
42 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
43 }
Tim Peters78be7992003-03-23 02:51:01 +000044#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000045 if (force || op->_ob_prev == NULL) {
46 op->_ob_next = refchain._ob_next;
47 op->_ob_prev = &refchain;
48 refchain._ob_next->_ob_prev = op;
49 refchain._ob_next = op;
50 }
51}
52#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000053
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000054#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000056extern int tuple_zero_allocs, fast_tuple_allocs;
57extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000058extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000059void
Fred Drake100814d2000-07-09 15:48:49 +000060dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000063
64 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000065 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000066 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000067 tp->tp_maxalloc);
68 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
69 fast_tuple_allocs, tuple_zero_allocs);
70 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
71 quick_int_allocs, quick_neg_int_allocs);
72 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
73 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074}
75
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000076PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000077get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000078{
79 PyTypeObject *tp;
80 PyObject *result;
81 PyObject *v;
82
83 result = PyList_New(0);
84 if (result == NULL)
85 return NULL;
86 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
88 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000089 if (v == NULL) {
90 Py_DECREF(result);
91 return NULL;
92 }
93 if (PyList_Append(result, v) < 0) {
94 Py_DECREF(v);
95 Py_DECREF(result);
96 return NULL;
97 }
98 Py_DECREF(v);
99 }
100 return result;
101}
102
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000103void
Fred Drake100814d2000-07-09 15:48:49 +0000104inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000105{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000106 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000107 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000108 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000110 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000111 /* Note that as of Python 2.2, heap-allocated type objects
112 * can go away, but this code requires that they stay alive
113 * until program exit. That's why we're careful with
114 * refcounts here. type_list gets a new reference to tp,
115 * while ownership of the reference type_list used to hold
116 * (if any) was transferred to tp->tp_next in the line above.
117 * tp is thus effectively immortal after this.
118 */
119 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000120 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000121#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000122 /* Also insert in the doubly-linked list of all objects,
123 * if not already there.
124 */
125 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000126#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000128 tp->tp_allocs++;
129 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
130 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000131}
132#endif
133
Tim Peters7c321a82002-07-09 02:57:01 +0000134#ifdef Py_REF_DEBUG
135/* Log a fatal error; doesn't return. */
136void
137_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
138{
139 char buf[300];
140
141 PyOS_snprintf(buf, sizeof(buf),
142 "%s:%i object at %p has negative ref count %i",
143 fname, lineno, op, op->ob_refcnt);
144 Py_FatalError(buf);
145}
146
147#endif /* Py_REF_DEBUG */
148
Thomas Heller1328b522004-04-22 17:23:49 +0000149void
150Py_IncRef(PyObject *o)
151{
152 Py_XINCREF(o);
153}
154
155void
156Py_DecRef(PyObject *o)
157{
158 Py_XDECREF(o);
159}
160
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000161PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000162PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000164 if (op == NULL)
165 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000166 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 return op;
170}
171
Guido van Rossumb18618d2000-05-03 23:44:39 +0000172PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000173PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000174{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000175 if (op == NULL)
176 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000177 /* Any changes should be reflected in PyObject_INIT_VAR */
178 op->ob_size = size;
179 op->ob_type = tp;
180 _Py_NewReference((PyObject *)op);
181 return op;
182}
183
184PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000185_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000186{
187 PyObject *op;
188 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
189 if (op == NULL)
190 return PyErr_NoMemory();
191 return PyObject_INIT(op, tp);
192}
193
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000194PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000195_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000197 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000198 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000199 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000201 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000202 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000203}
204
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000205/* for binary compatibility with 2.2 */
206#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000207void
Fred Drake100814d2000-07-09 15:48:49 +0000208_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000209{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000210 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211}
212
Neal Norwitz1a997502003-01-13 20:13:12 +0000213/* Implementation of PyObject_Print with recursion checking */
214static int
215internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Guido van Rossum278ef591991-07-27 21:40:24 +0000217 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000218 if (nesting > 10) {
219 PyErr_SetString(PyExc_RuntimeError, "print recursion");
220 return -1;
221 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000222 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000223 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000224#ifdef USE_STACKCHECK
225 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000226 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000227 return -1;
228 }
229#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000230 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000231 if (op == NULL) {
232 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233 }
Guido van Rossum90933611991-06-07 16:10:43 +0000234 else {
235 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000236 fprintf(fp, "<refcnt %u at %p>",
237 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000238 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000239 PyObject *s;
240 if (flags & Py_PRINT_RAW)
241 s = PyObject_Str(op);
242 else
243 s = PyObject_Repr(op);
244 if (s == NULL)
245 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000246 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000247 ret = internal_print(s, fp, Py_PRINT_RAW,
248 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000249 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000250 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000251 }
Guido van Rossum90933611991-06-07 16:10:43 +0000252 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000253 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000254 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000255 if (ret == 0) {
256 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000257 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000258 clearerr(fp);
259 ret = -1;
260 }
261 }
262 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263}
264
Neal Norwitz1a997502003-01-13 20:13:12 +0000265int
266PyObject_Print(PyObject *op, FILE *fp, int flags)
267{
268 return internal_print(op, fp, flags, 0);
269}
270
271
Barry Warsaw9bf16442001-01-23 16:24:35 +0000272/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000273void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000274{
Barry Warsaweefb1072001-02-22 22:39:18 +0000275 if (op == NULL)
276 fprintf(stderr, "NULL\n");
277 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000278 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000279 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000280 fprintf(stderr, "\n"
281 "type : %s\n"
282 "refcount: %d\n"
283 "address : %p\n",
284 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
285 op->ob_refcnt,
286 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000287 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000288}
Barry Warsaw903138f2001-01-23 16:33:18 +0000289
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000291PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000294 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000295#ifdef USE_STACKCHECK
296 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000297 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000298 return NULL;
299 }
300#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000301 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000303 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000304 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000305 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000306 else {
307 PyObject *res;
308 res = (*v->ob_type->tp_repr)(v);
309 if (res == NULL)
310 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000311#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000312 if (PyUnicode_Check(res)) {
313 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000314 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000315 Py_DECREF(res);
316 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000317 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000318 else
319 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000320 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000321#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000322 if (!PyString_Check(res)) {
323 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000324 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000325 res->ob_type->tp_name);
326 Py_DECREF(res);
327 return NULL;
328 }
329 return res;
330 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331}
332
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333PyObject *
Neil Schemenauercf52c072005-08-12 17:34:58 +0000334_PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000335{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000336 PyObject *res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000337 int type_ok;
Guido van Rossumc6004111993-11-05 10:22:19 +0000338 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000340 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000342 return v;
343 }
Neil Schemenauercf52c072005-08-12 17:34:58 +0000344#ifdef Py_USING_UNICODE
345 if (PyUnicode_CheckExact(v)) {
346 Py_INCREF(v);
347 return v;
348 }
349#endif
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000350 if (v->ob_type->tp_str == NULL)
351 return PyObject_Repr(v);
352
353 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000354 if (res == NULL)
355 return NULL;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000356 type_ok = PyString_Check(res);
357#ifdef Py_USING_UNICODE
358 type_ok = type_ok || PyUnicode_Check(res);
359#endif
360 if (!type_ok) {
361 PyErr_Format(PyExc_TypeError,
362 "__str__ returned non-string (type %.200s)",
363 res->ob_type->tp_name);
364 Py_DECREF(res);
365 return NULL;
366 }
367 return res;
368}
369
370PyObject *
371PyObject_Str(PyObject *v)
372{
373 PyObject *res = _PyObject_Str(v);
374 if (res == NULL)
375 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000376#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000377 if (PyUnicode_Check(res)) {
378 PyObject* str;
379 str = PyUnicode_AsEncodedString(res, NULL, NULL);
380 Py_DECREF(res);
381 if (str)
382 res = str;
383 else
384 return NULL;
385 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000386#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +0000387 assert(PyString_Check(res));
Guido van Rossum4c08d552000-03-10 22:55:18 +0000388 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000389}
390
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000391#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000392PyObject *
393PyObject_Unicode(PyObject *v)
394{
395 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000396 PyObject *func;
397 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000398
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000399 if (v == NULL)
400 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000401 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000402 Py_INCREF(v);
403 return v;
404 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000405 /* XXX As soon as we have a tp_unicode slot, we should
406 check this before trying the __unicode__
407 method. */
408 if (unicodestr == NULL) {
409 unicodestr= PyString_InternFromString("__unicode__");
410 if (unicodestr == NULL)
411 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000412 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000413 func = PyObject_GetAttr(v, unicodestr);
414 if (func != NULL) {
415 res = PyEval_CallObject(func, (PyObject *)NULL);
416 Py_DECREF(func);
417 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000418 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000419 PyErr_Clear();
420 if (PyUnicode_Check(v)) {
421 /* For a Unicode subtype that's didn't overwrite __unicode__,
422 return a true Unicode object with the same data. */
423 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
424 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000425 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000426 if (PyString_CheckExact(v)) {
427 Py_INCREF(v);
428 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000429 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000430 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000431 if (v->ob_type->tp_str != NULL)
432 res = (*v->ob_type->tp_str)(v);
433 else
434 res = PyObject_Repr(v);
435 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000436 }
437 if (res == NULL)
438 return NULL;
439 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000440 PyObject *str;
441 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000442 Py_DECREF(res);
443 if (str)
444 res = str;
445 else
Brett Cannonc3647ac2005-04-26 03:45:26 +0000446 return NULL;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000447 }
448 return res;
449}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000450#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000451
452
Guido van Rossuma4073002002-05-31 20:03:54 +0000453/* Helper to warn about deprecated tp_compare return values. Return:
454 -2 for an exception;
455 -1 if v < w;
456 0 if v == w;
457 1 if v > w.
458 (This function cannot return 2.)
459*/
460static int
461adjust_tp_compare(int c)
462{
463 if (PyErr_Occurred()) {
464 if (c != -1 && c != -2) {
465 PyObject *t, *v, *tb;
466 PyErr_Fetch(&t, &v, &tb);
467 if (PyErr_Warn(PyExc_RuntimeWarning,
468 "tp_compare didn't return -1 or -2 "
469 "for exception") < 0) {
470 Py_XDECREF(t);
471 Py_XDECREF(v);
472 Py_XDECREF(tb);
473 }
474 else
475 PyErr_Restore(t, v, tb);
476 }
477 return -2;
478 }
479 else if (c < -1 || c > 1) {
480 if (PyErr_Warn(PyExc_RuntimeWarning,
481 "tp_compare didn't return -1, 0 or 1") < 0)
482 return -2;
483 else
484 return c < -1 ? -1 : 1;
485 }
486 else {
487 assert(c >= -1 && c <= 1);
488 return c;
489 }
490}
491
492
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000493/* Macro to get the tp_richcompare field of a type if defined */
494#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
495 ? (t)->tp_richcompare : NULL)
496
Guido van Rossume797ec12001-01-17 15:24:28 +0000497/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000498int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000499
Guido van Rossume797ec12001-01-17 15:24:28 +0000500/* Try a genuine rich comparison, returning an object. Return:
501 NULL for exception;
502 NotImplemented if this particular rich comparison is not implemented or
503 undefined;
504 some object not equal to NotImplemented if it is implemented
505 (this latter object may not be a Boolean).
506*/
507static PyObject *
508try_rich_compare(PyObject *v, PyObject *w, int op)
509{
510 richcmpfunc f;
511 PyObject *res;
512
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000513 if (v->ob_type != w->ob_type &&
514 PyType_IsSubtype(w->ob_type, v->ob_type) &&
515 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000516 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000517 if (res != Py_NotImplemented)
518 return res;
519 Py_DECREF(res);
520 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000521 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000522 res = (*f)(v, w, op);
523 if (res != Py_NotImplemented)
524 return res;
525 Py_DECREF(res);
526 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000527 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000528 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000529 }
530 res = Py_NotImplemented;
531 Py_INCREF(res);
532 return res;
533}
534
535/* Try a genuine rich comparison, returning an int. Return:
536 -1 for exception (including the case where try_rich_compare() returns an
537 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000538 0 if the outcome is false;
539 1 if the outcome is true;
540 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000541*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000542static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000543try_rich_compare_bool(PyObject *v, PyObject *w, int op)
544{
545 PyObject *res;
546 int ok;
547
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000548 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000549 return 2; /* Shortcut, avoid INCREF+DECREF */
550 res = try_rich_compare(v, w, op);
551 if (res == NULL)
552 return -1;
553 if (res == Py_NotImplemented) {
554 Py_DECREF(res);
555 return 2;
556 }
557 ok = PyObject_IsTrue(res);
558 Py_DECREF(res);
559 return ok;
560}
561
562/* Try rich comparisons to determine a 3-way comparison. Return:
563 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000564 -1 if v < w;
565 0 if v == w;
566 1 if v > w;
567 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000568*/
569static int
570try_rich_to_3way_compare(PyObject *v, PyObject *w)
571{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000572 static struct { int op; int outcome; } tries[3] = {
573 /* Try this operator, and if it is true, use this outcome: */
574 {Py_EQ, 0},
575 {Py_LT, -1},
576 {Py_GT, 1},
577 };
578 int i;
579
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000580 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000581 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000582
583 for (i = 0; i < 3; i++) {
584 switch (try_rich_compare_bool(v, w, tries[i].op)) {
585 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000586 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000587 case 1:
588 return tries[i].outcome;
589 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000590 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000591
592 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000593}
594
595/* Try a 3-way comparison, returning an int. Return:
596 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000597 -1 if v < w;
598 0 if v == w;
599 1 if v > w;
600 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000601*/
602static int
603try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000604{
605 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000606 cmpfunc f;
607
608 /* Comparisons involving instances are given to instance_compare,
609 which has the same return conventions as this function. */
610
Guido van Rossumab3b0342001-09-18 20:38:53 +0000611 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000612 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000613 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000614 if (PyInstance_Check(w))
615 return (*w->ob_type->tp_compare)(v, w);
616
Guido van Rossumab3b0342001-09-18 20:38:53 +0000617 /* If both have the same (non-NULL) tp_compare, use it. */
618 if (f != NULL && f == w->ob_type->tp_compare) {
619 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000620 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000621 }
622
623 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
624 if (f == _PyObject_SlotCompare ||
625 w->ob_type->tp_compare == _PyObject_SlotCompare)
626 return _PyObject_SlotCompare(v, w);
627
Armin Rigoa1748132004-12-23 22:13:13 +0000628 /* If we're here, v and w,
629 a) are not instances;
630 b) have different types or a type without tp_compare; and
631 c) don't have a user-defined tp_compare.
632 tp_compare implementations in C assume that both arguments
633 have their type, so we give up if the coercion fails or if
634 it yields types which are still incompatible (which can
635 happen with a user-defined nb_coerce).
636 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000637 c = PyNumber_CoerceEx(&v, &w);
638 if (c < 0)
639 return -2;
640 if (c > 0)
641 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000642 f = v->ob_type->tp_compare;
643 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000644 c = (*f)(v, w);
645 Py_DECREF(v);
646 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000647 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000648 }
649
Guido van Rossume797ec12001-01-17 15:24:28 +0000650 /* No comparison defined */
651 Py_DECREF(v);
652 Py_DECREF(w);
653 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000654}
655
Guido van Rossume797ec12001-01-17 15:24:28 +0000656/* Final fallback 3-way comparison, returning an int. Return:
657 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000658 -1 if v < w;
659 0 if v == w;
660 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000661*/
662static int
663default_3way_compare(PyObject *v, PyObject *w)
664{
665 int c;
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000666 const char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000667
668 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000669 /* When comparing these pointers, they must be cast to
670 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
671 * uintptr_t). ANSI specifies that pointer compares other
672 * than == and != to non-related structures are undefined.
673 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000674 Py_uintptr_t vv = (Py_uintptr_t)v;
675 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000676 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
677 }
678
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000679#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000680 /* Special case for Unicode */
681 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
682 c = PyUnicode_Compare(v, w);
683 if (!PyErr_Occurred())
684 return c;
685 /* TypeErrors are ignored: if Unicode coercion fails due
686 to one of the arguments not having the right type, we
687 continue as defined by the coercion protocol (see
688 above). Luckily, decoding errors are reported as
689 ValueErrors and are not masked by this technique. */
690 if (!PyErr_ExceptionMatches(PyExc_TypeError))
691 return -2;
692 PyErr_Clear();
693 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000694#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000695
Guido van Rossum0871e932001-01-22 19:28:09 +0000696 /* None is smaller than anything */
697 if (v == Py_None)
698 return -1;
699 if (w == Py_None)
700 return 1;
701
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000702 /* different type: compare type names; numbers are smaller */
703 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000704 vname = "";
705 else
706 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000707 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000708 wname = "";
709 else
710 wname = w->ob_type->tp_name;
711 c = strcmp(vname, wname);
712 if (c < 0)
713 return -1;
714 if (c > 0)
715 return 1;
716 /* Same type name, or (more likely) incomparable numeric types */
717 return ((Py_uintptr_t)(v->ob_type) < (
718 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000719}
720
Tim Peters6d60b2e2001-05-07 20:53:51 +0000721/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000722 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000723 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000724 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000725 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000726 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000727 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000728*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000729static int
Fred Drake100814d2000-07-09 15:48:49 +0000730do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000731{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000732 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000733 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000734
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000735 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000736 && (f = v->ob_type->tp_compare) != NULL) {
737 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000738 if (PyInstance_Check(v)) {
739 /* Instance tp_compare has a different signature.
740 But if it returns undefined we fall through. */
741 if (c != 2)
742 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000743 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000744 }
745 else
746 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000747 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000748 /* We only get here if one of the following is true:
749 a) v and w have different types
750 b) v and w have the same type, which doesn't have tp_compare
751 c) v and w are instances, and either __cmp__ is not defined or
752 __cmp__ returns NotImplemented
753 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000754 c = try_rich_to_3way_compare(v, w);
755 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000756 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000757 c = try_3way_compare(v, w);
758 if (c < 2)
759 return c;
760 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000761}
762
Tim Petersc99213f2001-11-04 05:57:16 +0000763/* Compare v to w. Return
764 -1 if v < w or exception (PyErr_Occurred() true in latter case).
765 0 if v == w.
766 1 if v > w.
767 XXX The docs (C API manual) say the return value is undefined in case
768 XXX of error.
769*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000770int
Fred Drake100814d2000-07-09 15:48:49 +0000771PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000772{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000773 int result;
774
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000775 if (v == NULL || w == NULL) {
776 PyErr_BadInternalCall();
777 return -1;
778 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779 if (v == w)
780 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000781 if (Py_EnterRecursiveCall(" in cmp"))
782 return -1;
783 result = do_cmp(v, w);
784 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000785 return result < 0 ? -1 : result;
786}
787
Tim Petersc99213f2001-11-04 05:57:16 +0000788/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000789static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000790convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000791{
Guido van Rossume797ec12001-01-17 15:24:28 +0000792 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000793 switch (op) {
794 case Py_LT: c = c < 0; break;
795 case Py_LE: c = c <= 0; break;
796 case Py_EQ: c = c == 0; break;
797 case Py_NE: c = c != 0; break;
798 case Py_GT: c = c > 0; break;
799 case Py_GE: c = c >= 0; break;
800 }
801 result = c ? Py_True : Py_False;
802 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000803 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804}
Tim Peters803526b2002-07-07 05:13:56 +0000805
Tim Petersc99213f2001-11-04 05:57:16 +0000806/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
807 Return
808 NULL if error
809 Py_True if v op w
810 Py_False if not (v op w)
811*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000812static PyObject *
813try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
814{
815 int c;
816
817 c = try_3way_compare(v, w);
818 if (c >= 2)
819 c = default_3way_compare(v, w);
820 if (c <= -2)
821 return NULL;
822 return convert_3way_to_object(op, c);
823}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000824
Tim Petersc99213f2001-11-04 05:57:16 +0000825/* Do rich comparison on v and w. Return
826 NULL if error
827 Else a new reference to an object other than Py_NotImplemented, usually(?):
828 Py_True if v op w
829 Py_False if not (v op w)
830*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000831static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000832do_richcmp(PyObject *v, PyObject *w, int op)
833{
834 PyObject *res;
835
836 res = try_rich_compare(v, w, op);
837 if (res != Py_NotImplemented)
838 return res;
839 Py_DECREF(res);
840
841 return try_3way_to_rich_compare(v, w, op);
842}
843
Tim Petersc99213f2001-11-04 05:57:16 +0000844/* Return:
845 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000846 some object not equal to NotImplemented if it is implemented
847 (this latter object may not be a Boolean).
848*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000849PyObject *
850PyObject_RichCompare(PyObject *v, PyObject *w, int op)
851{
852 PyObject *res;
853
854 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000855 if (Py_EnterRecursiveCall(" in cmp"))
856 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000857
Armin Rigo2b3eb402003-10-28 12:05:48 +0000858 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000859 get out cheap (don't bother with coercions etc.). */
860 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
861 cmpfunc fcmp;
862 richcmpfunc frich = RICHCOMPARE(v->ob_type);
863 /* If the type has richcmp, try it first. try_rich_compare
864 tries it two-sided, which is not needed since we've a
865 single type only. */
866 if (frich != NULL) {
867 res = (*frich)(v, w, op);
868 if (res != Py_NotImplemented)
869 goto Done;
870 Py_DECREF(res);
871 }
872 /* No richcmp, or this particular richmp not implemented.
873 Try 3-way cmp. */
874 fcmp = v->ob_type->tp_compare;
875 if (fcmp != NULL) {
876 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000877 c = adjust_tp_compare(c);
878 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000879 res = NULL;
880 goto Done;
881 }
882 res = convert_3way_to_object(op, c);
883 goto Done;
884 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000885 }
Tim Peters67754e92001-11-04 07:29:31 +0000886
887 /* Fast path not taken, or couldn't deliver a useful result. */
888 res = do_richcmp(v, w, op);
889Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000890 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000891 return res;
892}
893
Tim Petersde9725f2001-05-05 10:06:17 +0000894/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000895int
896PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
897{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000898 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000899 int ok;
900
Raymond Hettinger93d44812004-03-21 17:01:44 +0000901 /* Quick result when objects are the same.
902 Guarantees that identity implies equality. */
903 if (v == w) {
904 if (op == Py_EQ)
905 return 1;
906 else if (op == Py_NE)
907 return 0;
908 }
909
910 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000911 if (res == NULL)
912 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000913 if (PyBool_Check(res))
914 ok = (res == Py_True);
915 else
916 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000917 Py_DECREF(res);
918 return ok;
919}
Fred Drake13634cf2000-06-29 19:17:04 +0000920
921/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000922 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000923
924 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
925*/
926
927long
Fred Drake100814d2000-07-09 15:48:49 +0000928_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000929{
Tim Peters39dce292000-08-15 03:34:48 +0000930 double intpart, fractpart;
931 int expo;
932 long hipart;
933 long x; /* the final hash value */
934 /* This is designed so that Python numbers of different types
935 * that compare equal hash to the same value; otherwise comparisons
936 * of mapping keys will turn out weird.
937 */
938
Tim Peters39dce292000-08-15 03:34:48 +0000939 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000940 if (fractpart == 0.0) {
941 /* This must return the same hash as an equal int or long. */
942 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
943 /* Convert to long and use its hash. */
944 PyObject *plong; /* converted to Python long */
945 if (Py_IS_INFINITY(intpart))
946 /* can't convert to long int -- arbitrary */
947 v = v < 0 ? -271828.0 : 314159.0;
948 plong = PyLong_FromDouble(v);
949 if (plong == NULL)
950 return -1;
951 x = PyObject_Hash(plong);
952 Py_DECREF(plong);
953 return x;
954 }
955 /* Fits in a C long == a Python int, so is its own hash. */
956 x = (long)intpart;
957 if (x == -1)
958 x = -2;
959 return x;
960 }
961 /* The fractional part is non-zero, so we don't have to worry about
962 * making this match the hash of some other type.
963 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000964 * Since the VAX D double format has 56 mantissa bits, which is the
965 * most of any double format in use, each of these parts may have as
966 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000967 * So, assuming sizeof(long) >= 4, each part can be broken into two
968 * longs; frexp and multiplication are used to do that.
969 * Also, since the Cray double format has 15 exponent bits, which is
970 * the most of any double format in use, shifting the exponent field
971 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000972 */
Tim Peters39dce292000-08-15 03:34:48 +0000973 v = frexp(v, &expo);
974 v *= 2147483648.0; /* 2**31 */
975 hipart = (long)v; /* take the top 32 bits */
976 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
977 x = hipart + (long)v + (expo << 15);
978 if (x == -1)
979 x = -2;
980 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000981}
982
983long
Fred Drake100814d2000-07-09 15:48:49 +0000984_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000985{
986#if SIZEOF_LONG >= SIZEOF_VOID_P
987 return (long)p;
988#else
989 /* convert to a Python long and hash that */
990 PyObject* longobj;
991 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000992
Fred Drake13634cf2000-06-29 19:17:04 +0000993 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
994 x = -1;
995 goto finally;
996 }
997 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000998
Fred Drake13634cf2000-06-29 19:17:04 +0000999finally:
1000 Py_XDECREF(longobj);
1001 return x;
1002#endif
1003}
1004
1005
Guido van Rossum9bfef441993-03-29 10:43:31 +00001006long
Fred Drake100814d2000-07-09 15:48:49 +00001007PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001008{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001009 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001010 if (tp->tp_hash != NULL)
1011 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001012 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001013 return _Py_HashPointer(v); /* Use address as hash value */
1014 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001015 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001016 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001017 return -1;
1018}
1019
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001020PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001021PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001022{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001023 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001024
Tim Peters6d6c1a32001-08-02 04:15:00 +00001025 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001026 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001027 w = PyString_InternFromString(name);
1028 if (w == NULL)
1029 return NULL;
1030 res = PyObject_GetAttr(v, w);
1031 Py_XDECREF(w);
1032 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001033}
1034
1035int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001036PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001037{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001038 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001039 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001040 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001041 return 1;
1042 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001043 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001044 return 0;
1045}
1046
1047int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001048PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001049{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050 PyObject *s;
1051 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001052
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001054 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001055 s = PyString_InternFromString(name);
1056 if (s == NULL)
1057 return -1;
1058 res = PyObject_SetAttr(v, s, w);
1059 Py_XDECREF(s);
1060 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001061}
1062
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001063PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001064PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001065{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 PyTypeObject *tp = v->ob_type;
1067
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001068 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001069#ifdef Py_USING_UNICODE
1070 /* The Unicode to string conversion is done here because the
1071 existing tp_getattro slots expect a string object as name
1072 and we wouldn't want to break those. */
1073 if (PyUnicode_Check(name)) {
1074 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1075 if (name == NULL)
1076 return NULL;
1077 }
1078 else
1079#endif
1080 {
1081 PyErr_SetString(PyExc_TypeError,
1082 "attribute name must be string");
1083 return NULL;
1084 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001085 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001086 if (tp->tp_getattro != NULL)
1087 return (*tp->tp_getattro)(v, name);
1088 if (tp->tp_getattr != NULL)
1089 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1090 PyErr_Format(PyExc_AttributeError,
1091 "'%.50s' object has no attribute '%.400s'",
1092 tp->tp_name, PyString_AS_STRING(name));
1093 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001094}
1095
1096int
Fred Drake100814d2000-07-09 15:48:49 +00001097PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001098{
1099 PyObject *res = PyObject_GetAttr(v, name);
1100 if (res != NULL) {
1101 Py_DECREF(res);
1102 return 1;
1103 }
1104 PyErr_Clear();
1105 return 0;
1106}
1107
1108int
Fred Drake100814d2000-07-09 15:48:49 +00001109PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001110{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001111 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001112 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001113
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001114 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001115#ifdef Py_USING_UNICODE
1116 /* The Unicode to string conversion is done here because the
1117 existing tp_setattro slots expect a string object as name
1118 and we wouldn't want to break those. */
1119 if (PyUnicode_Check(name)) {
1120 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1121 if (name == NULL)
1122 return -1;
1123 }
Tim Peters803526b2002-07-07 05:13:56 +00001124 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001125#endif
1126 {
1127 PyErr_SetString(PyExc_TypeError,
1128 "attribute name must be string");
1129 return -1;
1130 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001131 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001132 else
1133 Py_INCREF(name);
1134
1135 PyString_InternInPlace(&name);
1136 if (tp->tp_setattro != NULL) {
1137 err = (*tp->tp_setattro)(v, name, value);
1138 Py_DECREF(name);
1139 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001140 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001141 if (tp->tp_setattr != NULL) {
1142 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1143 Py_DECREF(name);
1144 return err;
1145 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001146 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1148 PyErr_Format(PyExc_TypeError,
1149 "'%.100s' object has no attributes "
1150 "(%s .%.100s)",
1151 tp->tp_name,
1152 value==NULL ? "del" : "assign to",
1153 PyString_AS_STRING(name));
1154 else
1155 PyErr_Format(PyExc_TypeError,
1156 "'%.100s' object has only read-only attributes "
1157 "(%s .%.100s)",
1158 tp->tp_name,
1159 value==NULL ? "del" : "assign to",
1160 PyString_AS_STRING(name));
1161 return -1;
1162}
1163
1164/* Helper to get a pointer to an object's __dict__ slot, if any */
1165
1166PyObject **
1167_PyObject_GetDictPtr(PyObject *obj)
1168{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 long dictoffset;
1170 PyTypeObject *tp = obj->ob_type;
1171
1172 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1173 return NULL;
1174 dictoffset = tp->tp_dictoffset;
1175 if (dictoffset == 0)
1176 return NULL;
1177 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001178 Py_ssize_t tsize;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001179 size_t size;
1180
1181 tsize = ((PyVarObject *)obj)->ob_size;
1182 if (tsize < 0)
1183 tsize = -tsize;
1184 size = _PyObject_VAR_SIZE(tp, tsize);
1185
Tim Peters6d483d32001-10-06 21:27:34 +00001186 dictoffset += (long)size;
1187 assert(dictoffset > 0);
1188 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 }
1190 return (PyObject **) ((char *)obj + dictoffset);
1191}
1192
Tim Peters6d6c1a32001-08-02 04:15:00 +00001193PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001194PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001195{
1196 Py_INCREF(obj);
1197 return obj;
1198}
1199
Michael W. Hudson1593f502004-09-14 17:09:47 +00001200/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1201
Raymond Hettinger01538262003-03-17 08:24:35 +00001202PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1204{
1205 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001206 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001207 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001209 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 PyObject **dictptr;
1211
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001212 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001213#ifdef Py_USING_UNICODE
1214 /* The Unicode to string conversion is done here because the
1215 existing tp_setattro slots expect a string object as name
1216 and we wouldn't want to break those. */
1217 if (PyUnicode_Check(name)) {
1218 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1219 if (name == NULL)
1220 return NULL;
1221 }
Tim Peters803526b2002-07-07 05:13:56 +00001222 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001223#endif
1224 {
1225 PyErr_SetString(PyExc_TypeError,
1226 "attribute name must be string");
1227 return NULL;
1228 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001229 }
1230 else
1231 Py_INCREF(name);
1232
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001234 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001235 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001236 }
1237
Guido van Rossum056fbf42002-08-19 19:22:50 +00001238 /* Inline _PyType_Lookup */
1239 {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001240 Py_ssize_t i, n;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001241 PyObject *mro, *base, *dict;
1242
1243 /* Look in tp_dict of types in MRO */
1244 mro = tp->tp_mro;
1245 assert(mro != NULL);
1246 assert(PyTuple_Check(mro));
1247 n = PyTuple_GET_SIZE(mro);
1248 for (i = 0; i < n; i++) {
1249 base = PyTuple_GET_ITEM(mro, i);
1250 if (PyClass_Check(base))
1251 dict = ((PyClassObject *)base)->cl_dict;
1252 else {
1253 assert(PyType_Check(base));
1254 dict = ((PyTypeObject *)base)->tp_dict;
1255 }
1256 assert(dict && PyDict_Check(dict));
1257 descr = PyDict_GetItem(dict, name);
1258 if (descr != NULL)
1259 break;
1260 }
1261 }
1262
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001263 Py_XINCREF(descr);
1264
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001266 if (descr != NULL &&
1267 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001269 if (f != NULL && PyDescr_IsData(descr)) {
1270 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001271 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001272 goto done;
1273 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274 }
1275
Guido van Rossumc66ff442002-08-19 16:50:48 +00001276 /* Inline _PyObject_GetDictPtr */
1277 dictoffset = tp->tp_dictoffset;
1278 if (dictoffset != 0) {
1279 PyObject *dict;
1280 if (dictoffset < 0) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001281 Py_ssize_t tsize;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001282 size_t size;
1283
1284 tsize = ((PyVarObject *)obj)->ob_size;
1285 if (tsize < 0)
1286 tsize = -tsize;
1287 size = _PyObject_VAR_SIZE(tp, tsize);
1288
1289 dictoffset += (long)size;
1290 assert(dictoffset > 0);
1291 assert(dictoffset % SIZEOF_VOID_P == 0);
1292 }
1293 dictptr = (PyObject **) ((char *)obj + dictoffset);
1294 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001296 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 if (res != NULL) {
1298 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001299 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001300 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 }
1302 }
1303 }
1304
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001305 if (f != NULL) {
1306 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001307 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001308 goto done;
1309 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310
1311 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001312 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001313 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001314 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001315 }
1316
1317 PyErr_Format(PyExc_AttributeError,
1318 "'%.50s' object has no attribute '%.400s'",
1319 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001320 done:
1321 Py_DECREF(name);
1322 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323}
1324
1325int
1326PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1327{
1328 PyTypeObject *tp = obj->ob_type;
1329 PyObject *descr;
1330 descrsetfunc f;
1331 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001332 int res = -1;
1333
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001334 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001335#ifdef Py_USING_UNICODE
1336 /* The Unicode to string conversion is done here because the
1337 existing tp_setattro slots expect a string object as name
1338 and we wouldn't want to break those. */
1339 if (PyUnicode_Check(name)) {
1340 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1341 if (name == NULL)
1342 return -1;
1343 }
Tim Peters803526b2002-07-07 05:13:56 +00001344 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001345#endif
1346 {
1347 PyErr_SetString(PyExc_TypeError,
1348 "attribute name must be string");
1349 return -1;
1350 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001351 }
1352 else
1353 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354
1355 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001356 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001357 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358 }
1359
1360 descr = _PyType_Lookup(tp, name);
1361 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001362 if (descr != NULL &&
1363 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001364 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001365 if (f != NULL && PyDescr_IsData(descr)) {
1366 res = f(descr, obj, value);
1367 goto done;
1368 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369 }
1370
1371 dictptr = _PyObject_GetDictPtr(obj);
1372 if (dictptr != NULL) {
1373 PyObject *dict = *dictptr;
1374 if (dict == NULL && value != NULL) {
1375 dict = PyDict_New();
1376 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001377 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378 *dictptr = dict;
1379 }
1380 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 if (value == NULL)
1382 res = PyDict_DelItem(dict, name);
1383 else
1384 res = PyDict_SetItem(dict, name, value);
1385 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1386 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001387 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001388 }
1389 }
1390
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001391 if (f != NULL) {
1392 res = f(descr, obj, value);
1393 goto done;
1394 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395
1396 if (descr == NULL) {
1397 PyErr_Format(PyExc_AttributeError,
1398 "'%.50s' object has no attribute '%.400s'",
1399 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001400 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401 }
1402
1403 PyErr_Format(PyExc_AttributeError,
1404 "'%.50s' object attribute '%.400s' is read-only",
1405 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001406 done:
1407 Py_DECREF(name);
1408 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001409}
1410
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001411/* Test a value used as condition, e.g., in a for or if statement.
1412 Return -1 if an error occurred */
1413
1414int
Fred Drake100814d2000-07-09 15:48:49 +00001415PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001416{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001417 Py_ssize_t res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001418 if (v == Py_True)
1419 return 1;
1420 if (v == Py_False)
1421 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001422 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001423 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001424 else if (v->ob_type->tp_as_number != NULL &&
1425 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001426 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001427 else if (v->ob_type->tp_as_mapping != NULL &&
1428 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001429 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001430 else if (v->ob_type->tp_as_sequence != NULL &&
1431 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001432 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1433 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001434 return 1;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001435 /* if it is negative, it should be either -1 or -2 */
1436 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001437}
1438
Tim Peters803526b2002-07-07 05:13:56 +00001439/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001440 Return -1 if an error occurred */
1441
1442int
Fred Drake100814d2000-07-09 15:48:49 +00001443PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001444{
1445 int res;
1446 res = PyObject_IsTrue(v);
1447 if (res < 0)
1448 return res;
1449 return res == 0;
1450}
1451
Guido van Rossum5524a591995-01-10 15:26:20 +00001452/* Coerce two numeric types to the "larger" one.
1453 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001454 Return value:
1455 -1 if an error occurred;
1456 0 if the coercion succeeded (and then the reference counts are increased);
1457 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001458*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001459int
Fred Drake100814d2000-07-09 15:48:49 +00001460PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001461{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001462 register PyObject *v = *pv;
1463 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001464 int res;
1465
Guido van Rossum517c7d42002-04-26 02:49:14 +00001466 /* Shortcut only for old-style types */
1467 if (v->ob_type == w->ob_type &&
1468 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1469 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001470 Py_INCREF(v);
1471 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001472 return 0;
1473 }
1474 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1475 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1476 if (res <= 0)
1477 return res;
1478 }
1479 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1480 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1481 if (res <= 0)
1482 return res;
1483 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001484 return 1;
1485}
1486
Guido van Rossume797ec12001-01-17 15:24:28 +00001487/* Coerce two numeric types to the "larger" one.
1488 Increment the reference count on each argument.
1489 Return -1 and raise an exception if no coercion is possible
1490 (and then no reference count is incremented).
1491*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001492int
Fred Drake100814d2000-07-09 15:48:49 +00001493PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001494{
1495 int err = PyNumber_CoerceEx(pv, pw);
1496 if (err <= 0)
1497 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001498 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001499 return -1;
1500}
1501
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001502
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001503/* Test whether an object can be called */
1504
1505int
Fred Drake100814d2000-07-09 15:48:49 +00001506PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001507{
1508 if (x == NULL)
1509 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001510 if (PyInstance_Check(x)) {
1511 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001512 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001513 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001514 return 0;
1515 }
1516 /* Could test recursively but don't, for fear of endless
1517 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001518 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001519 return 1;
1520 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001521 else {
1522 return x->ob_type->tp_call != NULL;
1523 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001524}
1525
Tim Peters7eea37e2001-09-04 22:08:56 +00001526/* Helper for PyObject_Dir.
1527 Merge the __dict__ of aclass into dict, and recursively also all
1528 the __dict__s of aclass's base classes. The order of merging isn't
1529 defined, as it's expected that only the final set of dict keys is
1530 interesting.
1531 Return 0 on success, -1 on error.
1532*/
1533
1534static int
1535merge_class_dict(PyObject* dict, PyObject* aclass)
1536{
1537 PyObject *classdict;
1538 PyObject *bases;
1539
1540 assert(PyDict_Check(dict));
1541 assert(aclass);
1542
1543 /* Merge in the type's dict (if any). */
1544 classdict = PyObject_GetAttrString(aclass, "__dict__");
1545 if (classdict == NULL)
1546 PyErr_Clear();
1547 else {
1548 int status = PyDict_Update(dict, classdict);
1549 Py_DECREF(classdict);
1550 if (status < 0)
1551 return -1;
1552 }
1553
1554 /* Recursively merge in the base types' (if any) dicts. */
1555 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001556 if (bases == NULL)
1557 PyErr_Clear();
1558 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001559 /* We have no guarantee that bases is a real tuple */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001560 Py_ssize_t i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001561 n = PySequence_Size(bases); /* This better be right */
1562 if (n < 0)
1563 PyErr_Clear();
1564 else {
1565 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001566 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001567 PyObject *base = PySequence_GetItem(bases, i);
1568 if (base == NULL) {
1569 Py_DECREF(bases);
1570 return -1;
1571 }
Tim Peters18e70832003-02-05 19:35:19 +00001572 status = merge_class_dict(dict, base);
1573 Py_DECREF(base);
1574 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001575 Py_DECREF(bases);
1576 return -1;
1577 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001578 }
1579 }
1580 Py_DECREF(bases);
1581 }
1582 return 0;
1583}
1584
Tim Peters305b5852001-09-17 02:38:46 +00001585/* Helper for PyObject_Dir.
1586 If obj has an attr named attrname that's a list, merge its string
1587 elements into keys of dict.
1588 Return 0 on success, -1 on error. Errors due to not finding the attr,
1589 or the attr not being a list, are suppressed.
1590*/
1591
1592static int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001593merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
Tim Peters305b5852001-09-17 02:38:46 +00001594{
1595 PyObject *list;
1596 int result = 0;
1597
1598 assert(PyDict_Check(dict));
1599 assert(obj);
1600 assert(attrname);
1601
1602 list = PyObject_GetAttrString(obj, attrname);
1603 if (list == NULL)
1604 PyErr_Clear();
1605
1606 else if (PyList_Check(list)) {
1607 int i;
1608 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1609 PyObject *item = PyList_GET_ITEM(list, i);
1610 if (PyString_Check(item)) {
1611 result = PyDict_SetItem(dict, item, Py_None);
1612 if (result < 0)
1613 break;
1614 }
1615 }
1616 }
1617
1618 Py_XDECREF(list);
1619 return result;
1620}
1621
Tim Peters7eea37e2001-09-04 22:08:56 +00001622/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1623 docstring, which should be kept in synch with this implementation. */
1624
1625PyObject *
1626PyObject_Dir(PyObject *arg)
1627{
1628 /* Set exactly one of these non-NULL before the end. */
1629 PyObject *result = NULL; /* result list */
1630 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1631
1632 /* If NULL arg, return the locals. */
1633 if (arg == NULL) {
1634 PyObject *locals = PyEval_GetLocals();
1635 if (locals == NULL)
1636 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001637 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001638 if (result == NULL)
1639 goto error;
1640 }
1641
1642 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001643 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001644 masterdict = PyObject_GetAttrString(arg, "__dict__");
1645 if (masterdict == NULL)
1646 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001647 if (!PyDict_Check(masterdict)) {
1648 PyErr_SetString(PyExc_TypeError,
1649 "module.__dict__ is not a dictionary");
1650 goto error;
1651 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001652 }
1653
1654 /* Elif some form of type or class, grab its dict and its bases.
1655 We deliberately don't suck up its __class__, as methods belonging
1656 to the metaclass would probably be more confusing than helpful. */
1657 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1658 masterdict = PyDict_New();
1659 if (masterdict == NULL)
1660 goto error;
1661 if (merge_class_dict(masterdict, arg) < 0)
1662 goto error;
1663 }
1664
1665 /* Else look at its dict, and the attrs reachable from its class. */
1666 else {
1667 PyObject *itsclass;
1668 /* Create a dict to start with. CAUTION: Not everything
1669 responding to __dict__ returns a dict! */
1670 masterdict = PyObject_GetAttrString(arg, "__dict__");
1671 if (masterdict == NULL) {
1672 PyErr_Clear();
1673 masterdict = PyDict_New();
1674 }
1675 else if (!PyDict_Check(masterdict)) {
1676 Py_DECREF(masterdict);
1677 masterdict = PyDict_New();
1678 }
1679 else {
1680 /* The object may have returned a reference to its
1681 dict, so copy it to avoid mutating it. */
1682 PyObject *temp = PyDict_Copy(masterdict);
1683 Py_DECREF(masterdict);
1684 masterdict = temp;
1685 }
1686 if (masterdict == NULL)
1687 goto error;
1688
Tim Peters305b5852001-09-17 02:38:46 +00001689 /* Merge in __members__ and __methods__ (if any).
1690 XXX Would like this to go away someday; for now, it's
1691 XXX needed to get at im_self etc of method objects. */
1692 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1693 goto error;
1694 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1695 goto error;
1696
Tim Peters7eea37e2001-09-04 22:08:56 +00001697 /* Merge in attrs reachable from its class.
1698 CAUTION: Not all objects have a __class__ attr. */
1699 itsclass = PyObject_GetAttrString(arg, "__class__");
1700 if (itsclass == NULL)
1701 PyErr_Clear();
1702 else {
1703 int status = merge_class_dict(masterdict, itsclass);
1704 Py_DECREF(itsclass);
1705 if (status < 0)
1706 goto error;
1707 }
1708 }
1709
1710 assert((result == NULL) ^ (masterdict == NULL));
1711 if (masterdict != NULL) {
1712 /* The result comes from its keys. */
1713 assert(result == NULL);
1714 result = PyDict_Keys(masterdict);
1715 if (result == NULL)
1716 goto error;
1717 }
1718
1719 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001720 if (!PyList_Check(result)) {
Tim Petersf4aca752004-09-23 02:39:37 +00001721 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001722 "Expected keys() to be a list.");
1723 goto error;
1724 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001725 if (PyList_Sort(result) != 0)
1726 goto error;
1727 else
1728 goto normal_return;
1729
1730 error:
1731 Py_XDECREF(result);
1732 result = NULL;
1733 /* fall through */
1734 normal_return:
1735 Py_XDECREF(masterdict);
1736 return result;
1737}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001738
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001739/*
1740NoObject is usable as a non-NULL undefined value, used by the macro None.
1741There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001742so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001743(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001744*/
1745
Guido van Rossum0c182a11992-03-27 17:26:13 +00001746/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001747static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001748none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001749{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001750 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001751}
1752
Barry Warsaw9bf16442001-01-23 16:24:35 +00001753/* ARGUSED */
1754static void
Tim Peters803526b2002-07-07 05:13:56 +00001755none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001756{
1757 /* This should never get called, but we also don't want to SEGV if
1758 * we accidently decref None out of existance.
1759 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001760 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001761}
1762
1763
Guido van Rossumba21a492001-08-16 08:17:26 +00001764static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001765 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001766 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001767 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001768 0,
1769 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001770 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001771 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001772 0, /*tp_getattr*/
1773 0, /*tp_setattr*/
1774 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001775 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001776 0, /*tp_as_number*/
1777 0, /*tp_as_sequence*/
1778 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001779 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001780};
1781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001782PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001783 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001784};
1785
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001786/* NotImplemented is an object that can be used to signal that an
1787 operation is not implemented for the given type combination. */
1788
1789static PyObject *
1790NotImplemented_repr(PyObject *op)
1791{
1792 return PyString_FromString("NotImplemented");
1793}
1794
1795static PyTypeObject PyNotImplemented_Type = {
1796 PyObject_HEAD_INIT(&PyType_Type)
1797 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001798 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001799 0,
1800 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001801 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001802 0, /*tp_print*/
1803 0, /*tp_getattr*/
1804 0, /*tp_setattr*/
1805 0, /*tp_compare*/
1806 (reprfunc)NotImplemented_repr, /*tp_repr*/
1807 0, /*tp_as_number*/
1808 0, /*tp_as_sequence*/
1809 0, /*tp_as_mapping*/
1810 0, /*tp_hash */
1811};
1812
1813PyObject _Py_NotImplementedStruct = {
1814 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1815};
1816
Guido van Rossumba21a492001-08-16 08:17:26 +00001817void
1818_Py_ReadyTypes(void)
1819{
1820 if (PyType_Ready(&PyType_Type) < 0)
1821 Py_FatalError("Can't initialize 'type'");
1822
Fred Drake0a4dd392004-07-02 18:57:45 +00001823 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1824 Py_FatalError("Can't initialize 'weakref'");
1825
Guido van Rossum77f6a652002-04-03 22:41:51 +00001826 if (PyType_Ready(&PyBool_Type) < 0)
1827 Py_FatalError("Can't initialize 'bool'");
1828
Guido van Rossumcacfc072002-05-24 19:01:59 +00001829 if (PyType_Ready(&PyString_Type) < 0)
1830 Py_FatalError("Can't initialize 'str'");
1831
Guido van Rossumba21a492001-08-16 08:17:26 +00001832 if (PyType_Ready(&PyList_Type) < 0)
1833 Py_FatalError("Can't initialize 'list'");
1834
1835 if (PyType_Ready(&PyNone_Type) < 0)
1836 Py_FatalError("Can't initialize type(None)");
1837
1838 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1839 Py_FatalError("Can't initialize type(NotImplemented)");
1840}
1841
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842
Guido van Rossum84a90321996-05-22 16:34:47 +00001843#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001845void
Fred Drake100814d2000-07-09 15:48:49 +00001846_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847{
Tim Peters34592512002-07-11 06:23:50 +00001848 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001850 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001851 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001852}
1853
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001854void
Fred Drake100814d2000-07-09 15:48:49 +00001855_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001856{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001857#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001858 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001859#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001860 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001861 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001862 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001863 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001864 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001865#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001866 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1867 if (p == op)
1868 break;
1869 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001870 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001871 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001872#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001873 op->_ob_next->_ob_prev = op->_ob_prev;
1874 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001875 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001876 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001877}
1878
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001879void
Fred Drake100814d2000-07-09 15:48:49 +00001880_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001881{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001882 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001883 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001884 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001885}
1886
Tim Peters269b2a62003-04-17 19:52:29 +00001887/* Print all live objects. Because PyObject_Print is called, the
1888 * interpreter must be in a healthy state.
1889 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001890void
Fred Drake100814d2000-07-09 15:48:49 +00001891_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001893 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001894 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001895 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001896 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001897 if (PyObject_Print(op, fp, 0) != 0)
1898 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001899 putc('\n', fp);
1900 }
1901}
1902
Tim Peters269b2a62003-04-17 19:52:29 +00001903/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1904 * doesn't make any calls to the Python C API, so is always safe to call.
1905 */
1906void
1907_Py_PrintReferenceAddresses(FILE *fp)
1908{
1909 PyObject *op;
1910 fprintf(fp, "Remaining object addresses:\n");
1911 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001912 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1913 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001914}
1915
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001916PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001917_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001918{
1919 int i, n;
1920 PyObject *t = NULL;
1921 PyObject *res, *op;
1922
1923 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1924 return NULL;
1925 op = refchain._ob_next;
1926 res = PyList_New(0);
1927 if (res == NULL)
1928 return NULL;
1929 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1930 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001931 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001932 op = op->_ob_next;
1933 if (op == &refchain)
1934 return res;
1935 }
1936 if (PyList_Append(res, op) < 0) {
1937 Py_DECREF(res);
1938 return NULL;
1939 }
1940 op = op->_ob_next;
1941 }
1942 return res;
1943}
1944
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001945#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001946
1947
1948/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001949PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001950
1951
1952/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001953Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001954
1955
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001956/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001957
Thomas Wouters334fb892000-07-25 12:56:38 +00001958void *
Fred Drake100814d2000-07-09 15:48:49 +00001959PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001960{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001961 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001962}
1963
Thomas Wouters334fb892000-07-25 12:56:38 +00001964void *
1965PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001966{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001967 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001968}
1969
1970void
Thomas Wouters334fb892000-07-25 12:56:38 +00001971PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001972{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001973 PyMem_FREE(p);
1974}
1975
1976
Guido van Rossum86610361998-04-10 22:32:46 +00001977/* These methods are used to control infinite recursion in repr, str, print,
1978 etc. Container objects that may recursively contain themselves,
1979 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1980 Py_ReprLeave() to avoid infinite recursion.
1981
1982 Py_ReprEnter() returns 0 the first time it is called for a particular
1983 object and 1 every time thereafter. It returns -1 if an exception
1984 occurred. Py_ReprLeave() has no return value.
1985
1986 See dictobject.c and listobject.c for examples of use.
1987*/
1988
1989#define KEY "Py_Repr"
1990
1991int
Fred Drake100814d2000-07-09 15:48:49 +00001992Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001993{
1994 PyObject *dict;
1995 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001996 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001997
1998 dict = PyThreadState_GetDict();
1999 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00002000 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002001 list = PyDict_GetItemString(dict, KEY);
2002 if (list == NULL) {
2003 list = PyList_New(0);
2004 if (list == NULL)
2005 return -1;
2006 if (PyDict_SetItemString(dict, KEY, list) < 0)
2007 return -1;
2008 Py_DECREF(list);
2009 }
2010 i = PyList_GET_SIZE(list);
2011 while (--i >= 0) {
2012 if (PyList_GET_ITEM(list, i) == obj)
2013 return 1;
2014 }
2015 PyList_Append(list, obj);
2016 return 0;
2017}
2018
2019void
Fred Drake100814d2000-07-09 15:48:49 +00002020Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002021{
2022 PyObject *dict;
2023 PyObject *list;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002024 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002025
2026 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002027 if (dict == NULL)
2028 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002029 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002030 if (list == NULL || !PyList_Check(list))
2031 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002032 i = PyList_GET_SIZE(list);
2033 /* Count backwards because we always expect obj to be list[-1] */
2034 while (--i >= 0) {
2035 if (PyList_GET_ITEM(list, i) == obj) {
2036 PyList_SetSlice(list, i, i + 1, NULL);
2037 break;
2038 }
2039 }
2040}
Guido van Rossumd724b232000-03-13 16:01:29 +00002041
Tim Peters803526b2002-07-07 05:13:56 +00002042/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002043
Tim Peters803526b2002-07-07 05:13:56 +00002044/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002045int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002046
Tim Peters803526b2002-07-07 05:13:56 +00002047/* List of objects that still need to be cleaned up, singly linked via their
2048 * gc headers' gc_prev pointers.
2049 */
2050PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002051
Tim Peters803526b2002-07-07 05:13:56 +00002052/* Add op to the _PyTrash_delete_later list. Called when the current
2053 * call-stack depth gets large. op must be a currently untracked gc'ed
2054 * object, with refcount 0. Py_DECREF must already have been called on it.
2055 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002056void
Fred Drake100814d2000-07-09 15:48:49 +00002057_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002058{
Tim Peters803526b2002-07-07 05:13:56 +00002059 assert(PyObject_IS_GC(op));
2060 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2061 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002062 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002063 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002064}
2065
Tim Peters803526b2002-07-07 05:13:56 +00002066/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2067 * the call-stack unwinds again.
2068 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002069void
Fred Drake100814d2000-07-09 15:48:49 +00002070_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002071{
2072 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002073 PyObject *op = _PyTrash_delete_later;
2074 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002075
Neil Schemenauerf589c052002-03-29 03:05:54 +00002076 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002077 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002078
Tim Peters803526b2002-07-07 05:13:56 +00002079 /* Call the deallocator directly. This used to try to
2080 * fool Py_DECREF into calling it indirectly, but
2081 * Py_DECREF was already called on this object, and in
2082 * assorted non-release builds calling Py_DECREF again ends
2083 * up distorting allocation statistics.
2084 */
2085 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002086 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002087 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002088 --_PyTrash_delete_nesting;
2089 }
2090}