blob: e9251cc22d47cf1a052876ecace2c60938469b3d [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
Jack Jansen28fc8802000-07-11 21:47:20 +00006#ifdef macintosh
7#include "macglue.h"
8#endif
9
Tim Peters34592512002-07-11 06:23:50 +000010#ifdef Py_REF_DEBUG
Mark Hammonda2905272002-07-29 13:42:14 +000011long _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Mark Hammonda2905272002-07-29 13:42:14 +000014int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000015
Guido van Rossum3f5da241990-12-20 15:06:42 +000016/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
17 These are used by the individual routines for object creation.
18 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000019
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000020#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000022extern int tuple_zero_allocs, fast_tuple_allocs;
23extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000024extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000025void
Fred Drake100814d2000-07-09 15:48:49 +000026dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000027{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000028 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000029
30 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000031 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000032 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000033 tp->tp_maxalloc);
34 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
35 fast_tuple_allocs, tuple_zero_allocs);
36 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
37 quick_int_allocs, quick_neg_int_allocs);
38 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
39 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000040}
41
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000042PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000043get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000044{
45 PyTypeObject *tp;
46 PyObject *result;
47 PyObject *v;
48
49 result = PyList_New(0);
50 if (result == NULL)
51 return NULL;
52 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000053 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
54 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000055 if (v == NULL) {
56 Py_DECREF(result);
57 return NULL;
58 }
59 if (PyList_Append(result, v) < 0) {
60 Py_DECREF(v);
61 Py_DECREF(result);
62 return NULL;
63 }
64 Py_DECREF(v);
65 }
66 return result;
67}
68
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000069void
Fred Drake100814d2000-07-09 15:48:49 +000070inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000071{
Tim Peters6d6c1a32001-08-02 04:15:00 +000072 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +000073 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +000077 /* Note that as of Python 2.2, heap-allocated type objects
78 * can go away, but this code requires that they stay alive
79 * until program exit. That's why we're careful with
80 * refcounts here. type_list gets a new reference to tp,
81 * while ownership of the reference type_list used to hold
82 * (if any) was transferred to tp->tp_next in the line above.
83 * tp is thus effectively immortal after this.
84 */
85 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000086 type_list = tp;
87 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000088 tp->tp_allocs++;
89 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
90 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000091}
92#endif
93
Tim Peters7c321a82002-07-09 02:57:01 +000094#ifdef Py_REF_DEBUG
95/* Log a fatal error; doesn't return. */
96void
97_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
98{
99 char buf[300];
100
101 PyOS_snprintf(buf, sizeof(buf),
102 "%s:%i object at %p has negative ref count %i",
103 fname, lineno, op, op->ob_refcnt);
104 Py_FatalError(buf);
105}
106
107#endif /* Py_REF_DEBUG */
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000110PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000112 if (op == NULL) {
113 PyErr_SetString(PyExc_SystemError,
114 "NULL object passed to PyObject_Init");
115 return op;
116 }
117 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000118 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000119 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000120 return op;
121}
122
Guido van Rossumb18618d2000-05-03 23:44:39 +0000123PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000124PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000125{
126 if (op == NULL) {
127 PyErr_SetString(PyExc_SystemError,
128 "NULL object passed to PyObject_InitVar");
129 return op;
130 }
131 /* Any changes should be reflected in PyObject_INIT_VAR */
132 op->ob_size = size;
133 op->ob_type = tp;
134 _Py_NewReference((PyObject *)op);
135 return op;
136}
137
138PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000139_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000140{
141 PyObject *op;
142 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
143 if (op == NULL)
144 return PyErr_NoMemory();
145 return PyObject_INIT(op, tp);
146}
147
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000148PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000149_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000151 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000152 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000153 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000155 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000156 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157}
158
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000159/* for binary compatibility with 2.2 */
160#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000161void
Fred Drake100814d2000-07-09 15:48:49 +0000162_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000163{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000164 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165}
166
Guido van Rossum90933611991-06-07 16:10:43 +0000167int
Fred Drake100814d2000-07-09 15:48:49 +0000168PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169{
Guido van Rossum278ef591991-07-27 21:40:24 +0000170 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000172 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000173#ifdef USE_STACKCHECK
174 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000175 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000176 return -1;
177 }
178#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000179 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000180 if (op == NULL) {
181 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000182 }
Guido van Rossum90933611991-06-07 16:10:43 +0000183 else {
184 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000185 fprintf(fp, "<refcnt %u at %p>",
186 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000187 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000188 PyObject *s;
189 if (flags & Py_PRINT_RAW)
190 s = PyObject_Str(op);
191 else
192 s = PyObject_Repr(op);
193 if (s == NULL)
194 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000195 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000196 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000197 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000198 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000199 }
Guido van Rossum90933611991-06-07 16:10:43 +0000200 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000201 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000202 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000203 if (ret == 0) {
204 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000206 clearerr(fp);
207 ret = -1;
208 }
209 }
210 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211}
212
Barry Warsaw9bf16442001-01-23 16:24:35 +0000213/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000214void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000215{
Barry Warsaweefb1072001-02-22 22:39:18 +0000216 if (op == NULL)
217 fprintf(stderr, "NULL\n");
218 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000219 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000220 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000221 fprintf(stderr, "\n"
222 "type : %s\n"
223 "refcount: %d\n"
224 "address : %p\n",
225 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
226 op->ob_refcnt,
227 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000228 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000229}
Barry Warsaw903138f2001-01-23 16:33:18 +0000230
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000232PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000235 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000236#ifdef USE_STACKCHECK
237 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000238 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000239 return NULL;
240 }
241#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000242 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000244 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000245 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000246 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000247 else {
248 PyObject *res;
249 res = (*v->ob_type->tp_repr)(v);
250 if (res == NULL)
251 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000252#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000253 if (PyUnicode_Check(res)) {
254 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000255 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000256 Py_DECREF(res);
257 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000258 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000259 else
260 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000261 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000262#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000263 if (!PyString_Check(res)) {
264 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000265 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000266 res->ob_type->tp_name);
267 Py_DECREF(res);
268 return NULL;
269 }
270 return res;
271 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272}
273
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000275PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000276{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000277 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000278
Guido van Rossumc6004111993-11-05 10:22:19 +0000279 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000280 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000281 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000283 return v;
284 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000285 if (v->ob_type->tp_str == NULL)
286 return PyObject_Repr(v);
287
288 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000289 if (res == NULL)
290 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000291#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000292 if (PyUnicode_Check(res)) {
293 PyObject* str;
294 str = PyUnicode_AsEncodedString(res, NULL, NULL);
295 Py_DECREF(res);
296 if (str)
297 res = str;
298 else
299 return NULL;
300 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000301#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000302 if (!PyString_Check(res)) {
303 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000304 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000305 res->ob_type->tp_name);
306 Py_DECREF(res);
307 return NULL;
308 }
309 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000310}
311
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000312#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000313PyObject *
314PyObject_Unicode(PyObject *v)
315{
316 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000317
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000318 if (v == NULL)
319 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000320 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000321 Py_INCREF(v);
322 return v;
323 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000324 if (PyUnicode_Check(v)) {
325 /* For a Unicode subtype that's not a Unicode object,
326 return a true Unicode object with the same data. */
327 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
328 PyUnicode_GET_SIZE(v));
329 }
330 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000331 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000332 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000333 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000334 else {
335 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000336 static PyObject *unicodestr;
337 /* XXX As soon as we have a tp_unicode slot, we should
338 check this before trying the __unicode__
339 method. */
340 if (unicodestr == NULL) {
341 unicodestr= PyString_InternFromString(
342 "__unicode__");
343 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000344 return NULL;
345 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000346 func = PyObject_GetAttr(v, unicodestr);
347 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000348 res = PyEval_CallObject(func, (PyObject *)NULL);
349 Py_DECREF(func);
350 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000351 else {
352 PyErr_Clear();
353 if (v->ob_type->tp_str != NULL)
354 res = (*v->ob_type->tp_str)(v);
355 else
356 res = PyObject_Repr(v);
357 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000358 }
359 if (res == NULL)
360 return NULL;
361 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000362 PyObject *str;
363 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000364 Py_DECREF(res);
365 if (str)
366 res = str;
367 else
368 return NULL;
369 }
370 return res;
371}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000372#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000373
374
Guido van Rossuma4073002002-05-31 20:03:54 +0000375/* Helper to warn about deprecated tp_compare return values. Return:
376 -2 for an exception;
377 -1 if v < w;
378 0 if v == w;
379 1 if v > w.
380 (This function cannot return 2.)
381*/
382static int
383adjust_tp_compare(int c)
384{
385 if (PyErr_Occurred()) {
386 if (c != -1 && c != -2) {
387 PyObject *t, *v, *tb;
388 PyErr_Fetch(&t, &v, &tb);
389 if (PyErr_Warn(PyExc_RuntimeWarning,
390 "tp_compare didn't return -1 or -2 "
391 "for exception") < 0) {
392 Py_XDECREF(t);
393 Py_XDECREF(v);
394 Py_XDECREF(tb);
395 }
396 else
397 PyErr_Restore(t, v, tb);
398 }
399 return -2;
400 }
401 else if (c < -1 || c > 1) {
402 if (PyErr_Warn(PyExc_RuntimeWarning,
403 "tp_compare didn't return -1, 0 or 1") < 0)
404 return -2;
405 else
406 return c < -1 ? -1 : 1;
407 }
408 else {
409 assert(c >= -1 && c <= 1);
410 return c;
411 }
412}
413
414
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000415/* Macro to get the tp_richcompare field of a type if defined */
416#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
417 ? (t)->tp_richcompare : NULL)
418
Guido van Rossume797ec12001-01-17 15:24:28 +0000419/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
420static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000421
Guido van Rossume797ec12001-01-17 15:24:28 +0000422/* Try a genuine rich comparison, returning an object. Return:
423 NULL for exception;
424 NotImplemented if this particular rich comparison is not implemented or
425 undefined;
426 some object not equal to NotImplemented if it is implemented
427 (this latter object may not be a Boolean).
428*/
429static PyObject *
430try_rich_compare(PyObject *v, PyObject *w, int op)
431{
432 richcmpfunc f;
433 PyObject *res;
434
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000435 if (v->ob_type != w->ob_type &&
436 PyType_IsSubtype(w->ob_type, v->ob_type) &&
437 (f = RICHCOMPARE(w->ob_type)) != NULL) {
438 res = (*f)(w, v, swapped_op[op]);
439 if (res != Py_NotImplemented)
440 return res;
441 Py_DECREF(res);
442 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000443 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000444 res = (*f)(v, w, op);
445 if (res != Py_NotImplemented)
446 return res;
447 Py_DECREF(res);
448 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000449 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000450 return (*f)(w, v, swapped_op[op]);
451 }
452 res = Py_NotImplemented;
453 Py_INCREF(res);
454 return res;
455}
456
457/* Try a genuine rich comparison, returning an int. Return:
458 -1 for exception (including the case where try_rich_compare() returns an
459 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000460 0 if the outcome is false;
461 1 if the outcome is true;
462 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000463*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000464static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000465try_rich_compare_bool(PyObject *v, PyObject *w, int op)
466{
467 PyObject *res;
468 int ok;
469
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000470 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000471 return 2; /* Shortcut, avoid INCREF+DECREF */
472 res = try_rich_compare(v, w, op);
473 if (res == NULL)
474 return -1;
475 if (res == Py_NotImplemented) {
476 Py_DECREF(res);
477 return 2;
478 }
479 ok = PyObject_IsTrue(res);
480 Py_DECREF(res);
481 return ok;
482}
483
484/* Try rich comparisons to determine a 3-way comparison. Return:
485 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000486 -1 if v < w;
487 0 if v == w;
488 1 if v > w;
489 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000490*/
491static int
492try_rich_to_3way_compare(PyObject *v, PyObject *w)
493{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000494 static struct { int op; int outcome; } tries[3] = {
495 /* Try this operator, and if it is true, use this outcome: */
496 {Py_EQ, 0},
497 {Py_LT, -1},
498 {Py_GT, 1},
499 };
500 int i;
501
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000502 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000503 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000504
505 for (i = 0; i < 3; i++) {
506 switch (try_rich_compare_bool(v, w, tries[i].op)) {
507 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000508 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000509 case 1:
510 return tries[i].outcome;
511 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000512 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000513
514 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000515}
516
517/* Try a 3-way comparison, returning an int. Return:
518 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000519 -1 if v < w;
520 0 if v == w;
521 1 if v > w;
522 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000523*/
524static int
525try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000526{
527 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000528 cmpfunc f;
529
530 /* Comparisons involving instances are given to instance_compare,
531 which has the same return conventions as this function. */
532
Guido van Rossumab3b0342001-09-18 20:38:53 +0000533 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000534 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000535 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000536 if (PyInstance_Check(w))
537 return (*w->ob_type->tp_compare)(v, w);
538
Guido van Rossumab3b0342001-09-18 20:38:53 +0000539 /* If both have the same (non-NULL) tp_compare, use it. */
540 if (f != NULL && f == w->ob_type->tp_compare) {
541 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000542 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000543 }
544
545 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
546 if (f == _PyObject_SlotCompare ||
547 w->ob_type->tp_compare == _PyObject_SlotCompare)
548 return _PyObject_SlotCompare(v, w);
549
Guido van Rossume797ec12001-01-17 15:24:28 +0000550 /* Try coercion; if it fails, give up */
551 c = PyNumber_CoerceEx(&v, &w);
552 if (c < 0)
553 return -2;
554 if (c > 0)
555 return 2;
556
557 /* Try v's comparison, if defined */
558 if ((f = v->ob_type->tp_compare) != NULL) {
559 c = (*f)(v, w);
560 Py_DECREF(v);
561 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000562 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000563 }
564
565 /* Try w's comparison, if defined */
566 if ((f = w->ob_type->tp_compare) != NULL) {
567 c = (*f)(w, v); /* swapped! */
568 Py_DECREF(v);
569 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000570 c = adjust_tp_compare(c);
571 if (c >= -1)
572 return -c; /* Swapped! */
573 else
574 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000575 }
576
577 /* No comparison defined */
578 Py_DECREF(v);
579 Py_DECREF(w);
580 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000581}
582
Guido van Rossume797ec12001-01-17 15:24:28 +0000583/* Final fallback 3-way comparison, returning an int. Return:
584 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000585 -1 if v < w;
586 0 if v == w;
587 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000588*/
589static int
590default_3way_compare(PyObject *v, PyObject *w)
591{
592 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000593 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000594
595 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000596 /* When comparing these pointers, they must be cast to
597 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
598 * uintptr_t). ANSI specifies that pointer compares other
599 * than == and != to non-related structures are undefined.
600 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000601 Py_uintptr_t vv = (Py_uintptr_t)v;
602 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000603 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
604 }
605
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000606#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000607 /* Special case for Unicode */
608 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
609 c = PyUnicode_Compare(v, w);
610 if (!PyErr_Occurred())
611 return c;
612 /* TypeErrors are ignored: if Unicode coercion fails due
613 to one of the arguments not having the right type, we
614 continue as defined by the coercion protocol (see
615 above). Luckily, decoding errors are reported as
616 ValueErrors and are not masked by this technique. */
617 if (!PyErr_ExceptionMatches(PyExc_TypeError))
618 return -2;
619 PyErr_Clear();
620 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000621#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000622
Guido van Rossum0871e932001-01-22 19:28:09 +0000623 /* None is smaller than anything */
624 if (v == Py_None)
625 return -1;
626 if (w == Py_None)
627 return 1;
628
Guido van Rossume797ec12001-01-17 15:24:28 +0000629 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000630 if (v->ob_type->tp_as_number)
631 vname = "";
632 else
633 vname = v->ob_type->tp_name;
634 if (w->ob_type->tp_as_number)
635 wname = "";
636 else
637 wname = w->ob_type->tp_name;
638 c = strcmp(vname, wname);
639 if (c < 0)
640 return -1;
641 if (c > 0)
642 return 1;
643 /* Same type name, or (more likely) incomparable numeric types */
644 return ((Py_uintptr_t)(v->ob_type) < (
645 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000646}
647
648#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
649
Tim Peters6d60b2e2001-05-07 20:53:51 +0000650/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000651 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000652 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000653 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000654 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000655 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000656 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000657*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000658static int
Fred Drake100814d2000-07-09 15:48:49 +0000659do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000660{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000661 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000662 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000663
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000664 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000665 && (f = v->ob_type->tp_compare) != NULL) {
666 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000667 if (PyInstance_Check(v)) {
668 /* Instance tp_compare has a different signature.
669 But if it returns undefined we fall through. */
670 if (c != 2)
671 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000672 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000673 }
674 else
675 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000676 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000677 /* We only get here if one of the following is true:
678 a) v and w have different types
679 b) v and w have the same type, which doesn't have tp_compare
680 c) v and w are instances, and either __cmp__ is not defined or
681 __cmp__ returns NotImplemented
682 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000683 c = try_rich_to_3way_compare(v, w);
684 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000685 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000686 c = try_3way_compare(v, w);
687 if (c < 2)
688 return c;
689 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000690}
691
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000692/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000693 some types) and decremented on exit. If the count exceeds the
694 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000695
696 This is a tunable parameter that should only affect the performance
697 of comparisons, nothing else. Setting it high makes comparing deeply
698 nested non-cyclical data structures faster, but makes comparing cyclical
699 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000700*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000701#define NESTING_LIMIT 20
702
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000703static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000704
705static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000706get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000707{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000708 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000709 PyObject *tstate_dict, *inprogress;
710
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000711 if (key == NULL) {
712 key = PyString_InternFromString("cmp_state");
713 if (key == NULL)
714 return NULL;
715 }
716
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000717 tstate_dict = PyThreadState_GetDict();
718 if (tstate_dict == NULL) {
719 PyErr_BadInternalCall();
720 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000721 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000722
Tim Peters803526b2002-07-07 05:13:56 +0000723 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000724 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000725 inprogress = PyDict_New();
726 if (inprogress == NULL)
727 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000728 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000729 Py_DECREF(inprogress);
730 return NULL;
731 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000732 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000733 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000734
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000735 return inprogress;
736}
737
738static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000739check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000740{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000741 PyObject *inprogress;
742 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000743 Py_uintptr_t iv = (Py_uintptr_t)v;
744 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000745 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000746
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000747 inprogress = get_inprogress_dict();
748 if (inprogress == NULL)
749 return NULL;
750
751 token = PyTuple_New(3);
752 if (token == NULL)
753 return NULL;
754
755 if (iv <= iw) {
756 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
757 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
758 if (op >= 0)
759 op = swapped_op[op];
760 } else {
761 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
762 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
763 }
764 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
765 if (x == NULL || y == NULL || z == NULL) {
766 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000767 return NULL;
768 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000769
770 if (PyDict_GetItem(inprogress, token) != NULL) {
771 Py_DECREF(token);
772 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000773 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000774
775 if (PyDict_SetItem(inprogress, token, token) < 0) {
776 Py_DECREF(token);
777 return NULL;
778 }
779
780 return token;
781}
782
783static void
784delete_token(PyObject *token)
785{
786 PyObject *inprogress;
787
788 if (token == NULL || token == Py_None)
789 return;
790 inprogress = get_inprogress_dict();
791 if (inprogress == NULL)
792 PyErr_Clear();
793 else
794 PyDict_DelItem(inprogress, token);
795 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000796}
797
Tim Petersc99213f2001-11-04 05:57:16 +0000798/* Compare v to w. Return
799 -1 if v < w or exception (PyErr_Occurred() true in latter case).
800 0 if v == w.
801 1 if v > w.
802 XXX The docs (C API manual) say the return value is undefined in case
803 XXX of error.
804*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805int
Fred Drake100814d2000-07-09 15:48:49 +0000806PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000808 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000809 int result;
810
Jack Jansend49cbe12000-08-22 21:52:51 +0000811#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000812 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000813 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000814 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000815 }
816#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000817 if (v == NULL || w == NULL) {
818 PyErr_BadInternalCall();
819 return -1;
820 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821 if (v == w)
822 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000823 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000824 compare_nesting++;
825 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000826 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000827 || (vtp->tp_as_sequence
828 && !PyString_Check(v)
829 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000830 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000831 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000832
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000833 if (token == NULL) {
834 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000835 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000836 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000837 /* already comparing these objects. assume
838 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000839 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000840 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000841 else {
842 result = do_cmp(v, w);
843 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000844 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000845 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000846 else {
847 result = do_cmp(v, w);
848 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000849 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000850 return result < 0 ? -1 : result;
851}
852
Tim Petersc99213f2001-11-04 05:57:16 +0000853/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000854static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000855convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000856{
Guido van Rossume797ec12001-01-17 15:24:28 +0000857 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000858 switch (op) {
859 case Py_LT: c = c < 0; break;
860 case Py_LE: c = c <= 0; break;
861 case Py_EQ: c = c == 0; break;
862 case Py_NE: c = c != 0; break;
863 case Py_GT: c = c > 0; break;
864 case Py_GE: c = c >= 0; break;
865 }
866 result = c ? Py_True : Py_False;
867 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000868 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000869}
Tim Peters803526b2002-07-07 05:13:56 +0000870
Tim Petersc99213f2001-11-04 05:57:16 +0000871/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
872 Return
873 NULL if error
874 Py_True if v op w
875 Py_False if not (v op w)
876*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000877static PyObject *
878try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
879{
880 int c;
881
882 c = try_3way_compare(v, w);
883 if (c >= 2)
884 c = default_3way_compare(v, w);
885 if (c <= -2)
886 return NULL;
887 return convert_3way_to_object(op, c);
888}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889
Tim Petersc99213f2001-11-04 05:57:16 +0000890/* Do rich comparison on v and w. Return
891 NULL if error
892 Else a new reference to an object other than Py_NotImplemented, usually(?):
893 Py_True if v op w
894 Py_False if not (v op w)
895*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000896static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000897do_richcmp(PyObject *v, PyObject *w, int op)
898{
899 PyObject *res;
900
901 res = try_rich_compare(v, w, op);
902 if (res != Py_NotImplemented)
903 return res;
904 Py_DECREF(res);
905
906 return try_3way_to_rich_compare(v, w, op);
907}
908
Tim Petersc99213f2001-11-04 05:57:16 +0000909/* Return:
910 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000911 some object not equal to NotImplemented if it is implemented
912 (this latter object may not be a Boolean).
913*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000914PyObject *
915PyObject_RichCompare(PyObject *v, PyObject *w, int op)
916{
917 PyObject *res;
918
919 assert(Py_LT <= op && op <= Py_GE);
920
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000921 compare_nesting++;
922 if (compare_nesting > NESTING_LIMIT &&
923 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000924 || (v->ob_type->tp_as_sequence
925 && !PyString_Check(v)
926 && !PyTuple_Check(v)))) {
Tim Peters67754e92001-11-04 07:29:31 +0000927
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000928 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000929 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000930 if (token == NULL) {
931 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000932 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000933 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000934 else if (token == Py_None) {
935 /* already comparing these objects with this operator.
936 assume they're equal until shown otherwise */
937 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000938 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000939 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000940 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000941 else {
942 PyErr_SetString(PyExc_ValueError,
943 "can't order recursive values");
944 res = NULL;
945 }
946 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000947 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000948 else {
949 res = do_richcmp(v, w, op);
950 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000951 }
Tim Peters67754e92001-11-04 07:29:31 +0000952 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000953 }
Tim Peters67754e92001-11-04 07:29:31 +0000954
955 /* No nesting extremism.
956 If the types are equal, and not old-style instances, try to
957 get out cheap (don't bother with coercions etc.). */
958 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
959 cmpfunc fcmp;
960 richcmpfunc frich = RICHCOMPARE(v->ob_type);
961 /* If the type has richcmp, try it first. try_rich_compare
962 tries it two-sided, which is not needed since we've a
963 single type only. */
964 if (frich != NULL) {
965 res = (*frich)(v, w, op);
966 if (res != Py_NotImplemented)
967 goto Done;
968 Py_DECREF(res);
969 }
970 /* No richcmp, or this particular richmp not implemented.
971 Try 3-way cmp. */
972 fcmp = v->ob_type->tp_compare;
973 if (fcmp != NULL) {
974 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000975 c = adjust_tp_compare(c);
976 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000977 res = NULL;
978 goto Done;
979 }
980 res = convert_3way_to_object(op, c);
981 goto Done;
982 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000983 }
Tim Peters67754e92001-11-04 07:29:31 +0000984
985 /* Fast path not taken, or couldn't deliver a useful result. */
986 res = do_richcmp(v, w, op);
987Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000988 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000989 return res;
990}
991
Tim Petersde9725f2001-05-05 10:06:17 +0000992/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000993int
994PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
995{
996 PyObject *res = PyObject_RichCompare(v, w, op);
997 int ok;
998
999 if (res == NULL)
1000 return -1;
1001 ok = PyObject_IsTrue(res);
1002 Py_DECREF(res);
1003 return ok;
1004}
Fred Drake13634cf2000-06-29 19:17:04 +00001005
1006/* Set of hash utility functions to help maintaining the invariant that
1007 iff a==b then hash(a)==hash(b)
1008
1009 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1010*/
1011
1012long
Fred Drake100814d2000-07-09 15:48:49 +00001013_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001014{
Tim Peters39dce292000-08-15 03:34:48 +00001015 double intpart, fractpart;
1016 int expo;
1017 long hipart;
1018 long x; /* the final hash value */
1019 /* This is designed so that Python numbers of different types
1020 * that compare equal hash to the same value; otherwise comparisons
1021 * of mapping keys will turn out weird.
1022 */
1023
1024#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1025{
1026 extended e;
1027 fractpart = modf(v, &e);
1028 intpart = e;
1029}
1030#else
1031 fractpart = modf(v, &intpart);
1032#endif
1033 if (fractpart == 0.0) {
1034 /* This must return the same hash as an equal int or long. */
1035 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1036 /* Convert to long and use its hash. */
1037 PyObject *plong; /* converted to Python long */
1038 if (Py_IS_INFINITY(intpart))
1039 /* can't convert to long int -- arbitrary */
1040 v = v < 0 ? -271828.0 : 314159.0;
1041 plong = PyLong_FromDouble(v);
1042 if (plong == NULL)
1043 return -1;
1044 x = PyObject_Hash(plong);
1045 Py_DECREF(plong);
1046 return x;
1047 }
1048 /* Fits in a C long == a Python int, so is its own hash. */
1049 x = (long)intpart;
1050 if (x == -1)
1051 x = -2;
1052 return x;
1053 }
1054 /* The fractional part is non-zero, so we don't have to worry about
1055 * making this match the hash of some other type.
1056 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001057 * Since the VAX D double format has 56 mantissa bits, which is the
1058 * most of any double format in use, each of these parts may have as
1059 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001060 * So, assuming sizeof(long) >= 4, each part can be broken into two
1061 * longs; frexp and multiplication are used to do that.
1062 * Also, since the Cray double format has 15 exponent bits, which is
1063 * the most of any double format in use, shifting the exponent field
1064 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001065 */
Tim Peters39dce292000-08-15 03:34:48 +00001066 v = frexp(v, &expo);
1067 v *= 2147483648.0; /* 2**31 */
1068 hipart = (long)v; /* take the top 32 bits */
1069 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1070 x = hipart + (long)v + (expo << 15);
1071 if (x == -1)
1072 x = -2;
1073 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001074}
1075
1076long
Fred Drake100814d2000-07-09 15:48:49 +00001077_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001078{
1079#if SIZEOF_LONG >= SIZEOF_VOID_P
1080 return (long)p;
1081#else
1082 /* convert to a Python long and hash that */
1083 PyObject* longobj;
1084 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001085
Fred Drake13634cf2000-06-29 19:17:04 +00001086 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1087 x = -1;
1088 goto finally;
1089 }
1090 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001091
Fred Drake13634cf2000-06-29 19:17:04 +00001092finally:
1093 Py_XDECREF(longobj);
1094 return x;
1095#endif
1096}
1097
1098
Guido van Rossum9bfef441993-03-29 10:43:31 +00001099long
Fred Drake100814d2000-07-09 15:48:49 +00001100PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001102 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001103 if (tp->tp_hash != NULL)
1104 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001105 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001106 return _Py_HashPointer(v); /* Use address as hash value */
1107 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001108 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001109 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001110 return -1;
1111}
1112
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001113PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001114PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001115{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001116 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001117
Tim Peters6d6c1a32001-08-02 04:15:00 +00001118 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001119 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120 w = PyString_InternFromString(name);
1121 if (w == NULL)
1122 return NULL;
1123 res = PyObject_GetAttr(v, w);
1124 Py_XDECREF(w);
1125 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001126}
1127
1128int
Fred Drake100814d2000-07-09 15:48:49 +00001129PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001130{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001131 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001132 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001133 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001134 return 1;
1135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001136 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001137 return 0;
1138}
1139
1140int
Fred Drake100814d2000-07-09 15:48:49 +00001141PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001142{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001143 PyObject *s;
1144 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001145
Tim Peters6d6c1a32001-08-02 04:15:00 +00001146 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001147 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148 s = PyString_InternFromString(name);
1149 if (s == NULL)
1150 return -1;
1151 res = PyObject_SetAttr(v, s, w);
1152 Py_XDECREF(s);
1153 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001154}
1155
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001156PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001157PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001158{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001159 PyTypeObject *tp = v->ob_type;
1160
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001161 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001162#ifdef Py_USING_UNICODE
1163 /* The Unicode to string conversion is done here because the
1164 existing tp_getattro slots expect a string object as name
1165 and we wouldn't want to break those. */
1166 if (PyUnicode_Check(name)) {
1167 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1168 if (name == NULL)
1169 return NULL;
1170 }
1171 else
1172#endif
1173 {
1174 PyErr_SetString(PyExc_TypeError,
1175 "attribute name must be string");
1176 return NULL;
1177 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001178 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179 if (tp->tp_getattro != NULL)
1180 return (*tp->tp_getattro)(v, name);
1181 if (tp->tp_getattr != NULL)
1182 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1183 PyErr_Format(PyExc_AttributeError,
1184 "'%.50s' object has no attribute '%.400s'",
1185 tp->tp_name, PyString_AS_STRING(name));
1186 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001187}
1188
1189int
Fred Drake100814d2000-07-09 15:48:49 +00001190PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001191{
1192 PyObject *res = PyObject_GetAttr(v, name);
1193 if (res != NULL) {
1194 Py_DECREF(res);
1195 return 1;
1196 }
1197 PyErr_Clear();
1198 return 0;
1199}
1200
1201int
Fred Drake100814d2000-07-09 15:48:49 +00001202PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001203{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001205 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001206
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001207 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001208#ifdef Py_USING_UNICODE
1209 /* The Unicode to string conversion is done here because the
1210 existing tp_setattro slots expect a string object as name
1211 and we wouldn't want to break those. */
1212 if (PyUnicode_Check(name)) {
1213 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1214 if (name == NULL)
1215 return -1;
1216 }
Tim Peters803526b2002-07-07 05:13:56 +00001217 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001218#endif
1219 {
1220 PyErr_SetString(PyExc_TypeError,
1221 "attribute name must be string");
1222 return -1;
1223 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001224 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 else
1226 Py_INCREF(name);
1227
1228 PyString_InternInPlace(&name);
1229 if (tp->tp_setattro != NULL) {
1230 err = (*tp->tp_setattro)(v, name, value);
1231 Py_DECREF(name);
1232 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001233 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 if (tp->tp_setattr != NULL) {
1235 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1236 Py_DECREF(name);
1237 return err;
1238 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001239 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1241 PyErr_Format(PyExc_TypeError,
1242 "'%.100s' object has no attributes "
1243 "(%s .%.100s)",
1244 tp->tp_name,
1245 value==NULL ? "del" : "assign to",
1246 PyString_AS_STRING(name));
1247 else
1248 PyErr_Format(PyExc_TypeError,
1249 "'%.100s' object has only read-only attributes "
1250 "(%s .%.100s)",
1251 tp->tp_name,
1252 value==NULL ? "del" : "assign to",
1253 PyString_AS_STRING(name));
1254 return -1;
1255}
1256
1257/* Helper to get a pointer to an object's __dict__ slot, if any */
1258
1259PyObject **
1260_PyObject_GetDictPtr(PyObject *obj)
1261{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262 long dictoffset;
1263 PyTypeObject *tp = obj->ob_type;
1264
1265 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1266 return NULL;
1267 dictoffset = tp->tp_dictoffset;
1268 if (dictoffset == 0)
1269 return NULL;
1270 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001271 int tsize;
1272 size_t size;
1273
1274 tsize = ((PyVarObject *)obj)->ob_size;
1275 if (tsize < 0)
1276 tsize = -tsize;
1277 size = _PyObject_VAR_SIZE(tp, tsize);
1278
Tim Peters6d483d32001-10-06 21:27:34 +00001279 dictoffset += (long)size;
1280 assert(dictoffset > 0);
1281 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282 }
1283 return (PyObject **) ((char *)obj + dictoffset);
1284}
1285
1286/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1287
1288PyObject *
1289PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1290{
1291 PyTypeObject *tp = obj->ob_type;
1292 PyObject *descr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001293 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 descrgetfunc f;
1295 PyObject **dictptr;
1296
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001297 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001298#ifdef Py_USING_UNICODE
1299 /* The Unicode to string conversion is done here because the
1300 existing tp_setattro slots expect a string object as name
1301 and we wouldn't want to break those. */
1302 if (PyUnicode_Check(name)) {
1303 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1304 if (name == NULL)
1305 return NULL;
1306 }
Tim Peters803526b2002-07-07 05:13:56 +00001307 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001308#endif
1309 {
1310 PyErr_SetString(PyExc_TypeError,
1311 "attribute name must be string");
1312 return NULL;
1313 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001314 }
1315 else
1316 Py_INCREF(name);
1317
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001319 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001320 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001321 }
1322
1323 descr = _PyType_Lookup(tp, name);
1324 f = NULL;
1325 if (descr != NULL) {
1326 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001327 if (f != NULL && PyDescr_IsData(descr)) {
1328 res = f(descr, obj, (PyObject *)obj->ob_type);
1329 goto done;
1330 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 }
1332
1333 dictptr = _PyObject_GetDictPtr(obj);
1334 if (dictptr != NULL) {
1335 PyObject *dict = *dictptr;
1336 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001337 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 if (res != NULL) {
1339 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001340 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341 }
1342 }
1343 }
1344
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001345 if (f != NULL) {
1346 res = f(descr, obj, (PyObject *)obj->ob_type);
1347 goto done;
1348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349
1350 if (descr != NULL) {
1351 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001352 res = descr;
1353 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354 }
1355
1356 PyErr_Format(PyExc_AttributeError,
1357 "'%.50s' object has no attribute '%.400s'",
1358 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 done:
1360 Py_DECREF(name);
1361 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362}
1363
1364int
1365PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1366{
1367 PyTypeObject *tp = obj->ob_type;
1368 PyObject *descr;
1369 descrsetfunc f;
1370 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001371 int res = -1;
1372
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001373 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001374#ifdef Py_USING_UNICODE
1375 /* The Unicode to string conversion is done here because the
1376 existing tp_setattro slots expect a string object as name
1377 and we wouldn't want to break those. */
1378 if (PyUnicode_Check(name)) {
1379 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1380 if (name == NULL)
1381 return -1;
1382 }
Tim Peters803526b2002-07-07 05:13:56 +00001383 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001384#endif
1385 {
1386 PyErr_SetString(PyExc_TypeError,
1387 "attribute name must be string");
1388 return -1;
1389 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001390 }
1391 else
1392 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393
1394 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001395 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001396 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001397 }
1398
1399 descr = _PyType_Lookup(tp, name);
1400 f = NULL;
1401 if (descr != NULL) {
1402 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001403 if (f != NULL && PyDescr_IsData(descr)) {
1404 res = f(descr, obj, value);
1405 goto done;
1406 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001407 }
1408
1409 dictptr = _PyObject_GetDictPtr(obj);
1410 if (dictptr != NULL) {
1411 PyObject *dict = *dictptr;
1412 if (dict == NULL && value != NULL) {
1413 dict = PyDict_New();
1414 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001415 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001416 *dictptr = dict;
1417 }
1418 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001419 if (value == NULL)
1420 res = PyDict_DelItem(dict, name);
1421 else
1422 res = PyDict_SetItem(dict, name, value);
1423 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1424 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001425 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001426 }
1427 }
1428
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001429 if (f != NULL) {
1430 res = f(descr, obj, value);
1431 goto done;
1432 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433
1434 if (descr == NULL) {
1435 PyErr_Format(PyExc_AttributeError,
1436 "'%.50s' object has no attribute '%.400s'",
1437 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001438 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001439 }
1440
1441 PyErr_Format(PyExc_AttributeError,
1442 "'%.50s' object attribute '%.400s' is read-only",
1443 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001444 done:
1445 Py_DECREF(name);
1446 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001447}
1448
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001449/* Test a value used as condition, e.g., in a for or if statement.
1450 Return -1 if an error occurred */
1451
1452int
Fred Drake100814d2000-07-09 15:48:49 +00001453PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001454{
1455 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001456 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001457 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001458 else if (v->ob_type->tp_as_number != NULL &&
1459 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001460 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001461 else if (v->ob_type->tp_as_mapping != NULL &&
1462 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001463 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001464 else if (v->ob_type->tp_as_sequence != NULL &&
1465 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001466 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1467 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001468 return 1;
1469 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001470}
1471
Tim Peters803526b2002-07-07 05:13:56 +00001472/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001473 Return -1 if an error occurred */
1474
1475int
Fred Drake100814d2000-07-09 15:48:49 +00001476PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001477{
1478 int res;
1479 res = PyObject_IsTrue(v);
1480 if (res < 0)
1481 return res;
1482 return res == 0;
1483}
1484
Guido van Rossum5524a591995-01-10 15:26:20 +00001485/* Coerce two numeric types to the "larger" one.
1486 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001487 Return value:
1488 -1 if an error occurred;
1489 0 if the coercion succeeded (and then the reference counts are increased);
1490 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001491*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001492int
Fred Drake100814d2000-07-09 15:48:49 +00001493PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001494{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001495 register PyObject *v = *pv;
1496 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001497 int res;
1498
Guido van Rossum517c7d42002-04-26 02:49:14 +00001499 /* Shortcut only for old-style types */
1500 if (v->ob_type == w->ob_type &&
1501 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1502 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001503 Py_INCREF(v);
1504 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001505 return 0;
1506 }
1507 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1508 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1509 if (res <= 0)
1510 return res;
1511 }
1512 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1513 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1514 if (res <= 0)
1515 return res;
1516 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001517 return 1;
1518}
1519
Guido van Rossume797ec12001-01-17 15:24:28 +00001520/* Coerce two numeric types to the "larger" one.
1521 Increment the reference count on each argument.
1522 Return -1 and raise an exception if no coercion is possible
1523 (and then no reference count is incremented).
1524*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001525int
Fred Drake100814d2000-07-09 15:48:49 +00001526PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001527{
1528 int err = PyNumber_CoerceEx(pv, pw);
1529 if (err <= 0)
1530 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001531 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001532 return -1;
1533}
1534
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001535
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001536/* Test whether an object can be called */
1537
1538int
Fred Drake100814d2000-07-09 15:48:49 +00001539PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001540{
1541 if (x == NULL)
1542 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001543 if (PyInstance_Check(x)) {
1544 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001545 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001546 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001547 return 0;
1548 }
1549 /* Could test recursively but don't, for fear of endless
1550 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001551 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001552 return 1;
1553 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001554 else {
1555 return x->ob_type->tp_call != NULL;
1556 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001557}
1558
Tim Peters7eea37e2001-09-04 22:08:56 +00001559/* Helper for PyObject_Dir.
1560 Merge the __dict__ of aclass into dict, and recursively also all
1561 the __dict__s of aclass's base classes. The order of merging isn't
1562 defined, as it's expected that only the final set of dict keys is
1563 interesting.
1564 Return 0 on success, -1 on error.
1565*/
1566
1567static int
1568merge_class_dict(PyObject* dict, PyObject* aclass)
1569{
1570 PyObject *classdict;
1571 PyObject *bases;
1572
1573 assert(PyDict_Check(dict));
1574 assert(aclass);
1575
1576 /* Merge in the type's dict (if any). */
1577 classdict = PyObject_GetAttrString(aclass, "__dict__");
1578 if (classdict == NULL)
1579 PyErr_Clear();
1580 else {
1581 int status = PyDict_Update(dict, classdict);
1582 Py_DECREF(classdict);
1583 if (status < 0)
1584 return -1;
1585 }
1586
1587 /* Recursively merge in the base types' (if any) dicts. */
1588 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001589 if (bases == NULL)
1590 PyErr_Clear();
1591 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001592 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001593 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001594 n = PySequence_Size(bases); /* This better be right */
1595 if (n < 0)
1596 PyErr_Clear();
1597 else {
1598 for (i = 0; i < n; i++) {
1599 PyObject *base = PySequence_GetItem(bases, i);
1600 if (base == NULL) {
1601 Py_DECREF(bases);
1602 return -1;
1603 }
1604 if (merge_class_dict(dict, base) < 0) {
1605 Py_DECREF(bases);
1606 return -1;
1607 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001608 }
1609 }
1610 Py_DECREF(bases);
1611 }
1612 return 0;
1613}
1614
Tim Peters305b5852001-09-17 02:38:46 +00001615/* Helper for PyObject_Dir.
1616 If obj has an attr named attrname that's a list, merge its string
1617 elements into keys of dict.
1618 Return 0 on success, -1 on error. Errors due to not finding the attr,
1619 or the attr not being a list, are suppressed.
1620*/
1621
1622static int
1623merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1624{
1625 PyObject *list;
1626 int result = 0;
1627
1628 assert(PyDict_Check(dict));
1629 assert(obj);
1630 assert(attrname);
1631
1632 list = PyObject_GetAttrString(obj, attrname);
1633 if (list == NULL)
1634 PyErr_Clear();
1635
1636 else if (PyList_Check(list)) {
1637 int i;
1638 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1639 PyObject *item = PyList_GET_ITEM(list, i);
1640 if (PyString_Check(item)) {
1641 result = PyDict_SetItem(dict, item, Py_None);
1642 if (result < 0)
1643 break;
1644 }
1645 }
1646 }
1647
1648 Py_XDECREF(list);
1649 return result;
1650}
1651
Tim Peters7eea37e2001-09-04 22:08:56 +00001652/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1653 docstring, which should be kept in synch with this implementation. */
1654
1655PyObject *
1656PyObject_Dir(PyObject *arg)
1657{
1658 /* Set exactly one of these non-NULL before the end. */
1659 PyObject *result = NULL; /* result list */
1660 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1661
1662 /* If NULL arg, return the locals. */
1663 if (arg == NULL) {
1664 PyObject *locals = PyEval_GetLocals();
1665 if (locals == NULL)
1666 goto error;
1667 result = PyDict_Keys(locals);
1668 if (result == NULL)
1669 goto error;
1670 }
1671
1672 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001673 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001674 masterdict = PyObject_GetAttrString(arg, "__dict__");
1675 if (masterdict == NULL)
1676 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001677 if (!PyDict_Check(masterdict)) {
1678 PyErr_SetString(PyExc_TypeError,
1679 "module.__dict__ is not a dictionary");
1680 goto error;
1681 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001682 }
1683
1684 /* Elif some form of type or class, grab its dict and its bases.
1685 We deliberately don't suck up its __class__, as methods belonging
1686 to the metaclass would probably be more confusing than helpful. */
1687 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1688 masterdict = PyDict_New();
1689 if (masterdict == NULL)
1690 goto error;
1691 if (merge_class_dict(masterdict, arg) < 0)
1692 goto error;
1693 }
1694
1695 /* Else look at its dict, and the attrs reachable from its class. */
1696 else {
1697 PyObject *itsclass;
1698 /* Create a dict to start with. CAUTION: Not everything
1699 responding to __dict__ returns a dict! */
1700 masterdict = PyObject_GetAttrString(arg, "__dict__");
1701 if (masterdict == NULL) {
1702 PyErr_Clear();
1703 masterdict = PyDict_New();
1704 }
1705 else if (!PyDict_Check(masterdict)) {
1706 Py_DECREF(masterdict);
1707 masterdict = PyDict_New();
1708 }
1709 else {
1710 /* The object may have returned a reference to its
1711 dict, so copy it to avoid mutating it. */
1712 PyObject *temp = PyDict_Copy(masterdict);
1713 Py_DECREF(masterdict);
1714 masterdict = temp;
1715 }
1716 if (masterdict == NULL)
1717 goto error;
1718
Tim Peters305b5852001-09-17 02:38:46 +00001719 /* Merge in __members__ and __methods__ (if any).
1720 XXX Would like this to go away someday; for now, it's
1721 XXX needed to get at im_self etc of method objects. */
1722 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1723 goto error;
1724 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1725 goto error;
1726
Tim Peters7eea37e2001-09-04 22:08:56 +00001727 /* Merge in attrs reachable from its class.
1728 CAUTION: Not all objects have a __class__ attr. */
1729 itsclass = PyObject_GetAttrString(arg, "__class__");
1730 if (itsclass == NULL)
1731 PyErr_Clear();
1732 else {
1733 int status = merge_class_dict(masterdict, itsclass);
1734 Py_DECREF(itsclass);
1735 if (status < 0)
1736 goto error;
1737 }
1738 }
1739
1740 assert((result == NULL) ^ (masterdict == NULL));
1741 if (masterdict != NULL) {
1742 /* The result comes from its keys. */
1743 assert(result == NULL);
1744 result = PyDict_Keys(masterdict);
1745 if (result == NULL)
1746 goto error;
1747 }
1748
1749 assert(result);
1750 if (PyList_Sort(result) != 0)
1751 goto error;
1752 else
1753 goto normal_return;
1754
1755 error:
1756 Py_XDECREF(result);
1757 result = NULL;
1758 /* fall through */
1759 normal_return:
1760 Py_XDECREF(masterdict);
1761 return result;
1762}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001763
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001764/*
1765NoObject is usable as a non-NULL undefined value, used by the macro None.
1766There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001767so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001768(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001769*/
1770
Guido van Rossum0c182a11992-03-27 17:26:13 +00001771/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001772static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001773none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001774{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001775 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001776}
1777
Barry Warsaw9bf16442001-01-23 16:24:35 +00001778/* ARGUSED */
1779static void
Tim Peters803526b2002-07-07 05:13:56 +00001780none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001781{
1782 /* This should never get called, but we also don't want to SEGV if
1783 * we accidently decref None out of existance.
1784 */
1785 abort();
1786}
1787
1788
Guido van Rossumba21a492001-08-16 08:17:26 +00001789static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001790 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001791 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001792 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001793 0,
1794 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001795 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001796 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001797 0, /*tp_getattr*/
1798 0, /*tp_setattr*/
1799 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001800 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001801 0, /*tp_as_number*/
1802 0, /*tp_as_sequence*/
1803 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001804 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001805};
1806
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001807PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001808 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001809};
1810
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001811/* NotImplemented is an object that can be used to signal that an
1812 operation is not implemented for the given type combination. */
1813
1814static PyObject *
1815NotImplemented_repr(PyObject *op)
1816{
1817 return PyString_FromString("NotImplemented");
1818}
1819
1820static PyTypeObject PyNotImplemented_Type = {
1821 PyObject_HEAD_INIT(&PyType_Type)
1822 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001823 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001824 0,
1825 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001826 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001827 0, /*tp_print*/
1828 0, /*tp_getattr*/
1829 0, /*tp_setattr*/
1830 0, /*tp_compare*/
1831 (reprfunc)NotImplemented_repr, /*tp_repr*/
1832 0, /*tp_as_number*/
1833 0, /*tp_as_sequence*/
1834 0, /*tp_as_mapping*/
1835 0, /*tp_hash */
1836};
1837
1838PyObject _Py_NotImplementedStruct = {
1839 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1840};
1841
Guido van Rossumba21a492001-08-16 08:17:26 +00001842void
1843_Py_ReadyTypes(void)
1844{
1845 if (PyType_Ready(&PyType_Type) < 0)
1846 Py_FatalError("Can't initialize 'type'");
1847
Guido van Rossum77f6a652002-04-03 22:41:51 +00001848 if (PyType_Ready(&PyBool_Type) < 0)
1849 Py_FatalError("Can't initialize 'bool'");
1850
Guido van Rossumcacfc072002-05-24 19:01:59 +00001851 if (PyType_Ready(&PyString_Type) < 0)
1852 Py_FatalError("Can't initialize 'str'");
1853
Guido van Rossumba21a492001-08-16 08:17:26 +00001854 if (PyType_Ready(&PyList_Type) < 0)
1855 Py_FatalError("Can't initialize 'list'");
1856
1857 if (PyType_Ready(&PyNone_Type) < 0)
1858 Py_FatalError("Can't initialize type(None)");
1859
1860 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1861 Py_FatalError("Can't initialize type(NotImplemented)");
1862}
1863
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001864
Guido van Rossum84a90321996-05-22 16:34:47 +00001865#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001866
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001867static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001868
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001869void
Fred Drake100814d2000-07-09 15:48:49 +00001870_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001871{
1872 refchain._ob_prev = refchain._ob_next = &refchain;
1873 _Py_RefTotal = 0;
1874}
1875
1876void
Fred Drake100814d2000-07-09 15:48:49 +00001877_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001878{
Tim Peters34592512002-07-11 06:23:50 +00001879 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880 op->ob_refcnt = 1;
1881 op->_ob_next = refchain._ob_next;
1882 op->_ob_prev = &refchain;
1883 refchain._ob_next->_ob_prev = op;
1884 refchain._ob_next = op;
Tim Peters34592512002-07-11 06:23:50 +00001885 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001886}
1887
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001888void
Fred Drake100814d2000-07-09 15:48:49 +00001889_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001890{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001891#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001892 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001893#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001894 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001895 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001896 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001897 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001898 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001899#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001900 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1901 if (p == op)
1902 break;
1903 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001904 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001905 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001906#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001907 op->_ob_next->_ob_prev = op->_ob_prev;
1908 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001909 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001910 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001911}
1912
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001913void
Fred Drake100814d2000-07-09 15:48:49 +00001914_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001915{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001916 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001917 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001918 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001919}
1920
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001921void
Fred Drake100814d2000-07-09 15:48:49 +00001922_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001923{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001924 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001925 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001926 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1927 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001928 if (PyObject_Print(op, fp, 0) != 0)
1929 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001930 putc('\n', fp);
1931 }
1932}
1933
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001934PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001935_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001936{
1937 int i, n;
1938 PyObject *t = NULL;
1939 PyObject *res, *op;
1940
1941 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1942 return NULL;
1943 op = refchain._ob_next;
1944 res = PyList_New(0);
1945 if (res == NULL)
1946 return NULL;
1947 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1948 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001949 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001950 op = op->_ob_next;
1951 if (op == &refchain)
1952 return res;
1953 }
1954 if (PyList_Append(res, op) < 0) {
1955 Py_DECREF(res);
1956 return NULL;
1957 }
1958 op = op->_ob_next;
1959 }
1960 return res;
1961}
1962
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001963#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001964
1965
1966/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001967PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001968
1969
1970/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001971int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001972
1973
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001974/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001975
Thomas Wouters334fb892000-07-25 12:56:38 +00001976void *
Fred Drake100814d2000-07-09 15:48:49 +00001977PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001978{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001979 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001980}
1981
Thomas Wouters334fb892000-07-25 12:56:38 +00001982void *
1983PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001984{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001985 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001986}
1987
1988void
Thomas Wouters334fb892000-07-25 12:56:38 +00001989PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001990{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001991 PyMem_FREE(p);
1992}
1993
1994
Guido van Rossum86610361998-04-10 22:32:46 +00001995/* These methods are used to control infinite recursion in repr, str, print,
1996 etc. Container objects that may recursively contain themselves,
1997 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1998 Py_ReprLeave() to avoid infinite recursion.
1999
2000 Py_ReprEnter() returns 0 the first time it is called for a particular
2001 object and 1 every time thereafter. It returns -1 if an exception
2002 occurred. Py_ReprLeave() has no return value.
2003
2004 See dictobject.c and listobject.c for examples of use.
2005*/
2006
2007#define KEY "Py_Repr"
2008
2009int
Fred Drake100814d2000-07-09 15:48:49 +00002010Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002011{
2012 PyObject *dict;
2013 PyObject *list;
2014 int i;
2015
2016 dict = PyThreadState_GetDict();
2017 if (dict == NULL)
2018 return -1;
2019 list = PyDict_GetItemString(dict, KEY);
2020 if (list == NULL) {
2021 list = PyList_New(0);
2022 if (list == NULL)
2023 return -1;
2024 if (PyDict_SetItemString(dict, KEY, list) < 0)
2025 return -1;
2026 Py_DECREF(list);
2027 }
2028 i = PyList_GET_SIZE(list);
2029 while (--i >= 0) {
2030 if (PyList_GET_ITEM(list, i) == obj)
2031 return 1;
2032 }
2033 PyList_Append(list, obj);
2034 return 0;
2035}
2036
2037void
Fred Drake100814d2000-07-09 15:48:49 +00002038Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002039{
2040 PyObject *dict;
2041 PyObject *list;
2042 int i;
2043
2044 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002045 if (dict == NULL)
2046 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002047 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002048 if (list == NULL || !PyList_Check(list))
2049 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002050 i = PyList_GET_SIZE(list);
2051 /* Count backwards because we always expect obj to be list[-1] */
2052 while (--i >= 0) {
2053 if (PyList_GET_ITEM(list, i) == obj) {
2054 PyList_SetSlice(list, i, i + 1, NULL);
2055 break;
2056 }
2057 }
2058}
Guido van Rossumd724b232000-03-13 16:01:29 +00002059
Tim Peters803526b2002-07-07 05:13:56 +00002060/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002061
Tim Peters803526b2002-07-07 05:13:56 +00002062/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002063int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002064
Tim Peters803526b2002-07-07 05:13:56 +00002065/* List of objects that still need to be cleaned up, singly linked via their
2066 * gc headers' gc_prev pointers.
2067 */
2068PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002069
Tim Peters803526b2002-07-07 05:13:56 +00002070/* Add op to the _PyTrash_delete_later list. Called when the current
2071 * call-stack depth gets large. op must be a currently untracked gc'ed
2072 * object, with refcount 0. Py_DECREF must already have been called on it.
2073 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002074void
Fred Drake100814d2000-07-09 15:48:49 +00002075_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002076{
Tim Peters803526b2002-07-07 05:13:56 +00002077 assert(PyObject_IS_GC(op));
2078 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2079 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002080 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002081 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002082}
2083
Tim Peters803526b2002-07-07 05:13:56 +00002084/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2085 * the call-stack unwinds again.
2086 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002087void
Fred Drake100814d2000-07-09 15:48:49 +00002088_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002089{
2090 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002091 PyObject *op = _PyTrash_delete_later;
2092 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002093
Neil Schemenauerf589c052002-03-29 03:05:54 +00002094 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002095 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002096
Tim Peters803526b2002-07-07 05:13:56 +00002097 /* Call the deallocator directly. This used to try to
2098 * fool Py_DECREF into calling it indirectly, but
2099 * Py_DECREF was already called on this object, and in
2100 * assorted non-release builds calling Py_DECREF again ends
2101 * up distorting allocation statistics.
2102 */
2103 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002104 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002105 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002106 --_PyTrash_delete_nesting;
2107 }
2108}