blob: fd069f1fe637dbdd389a0b3454219b7955e94a38 [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
Guido van Rossum6f9e4331995-03-29 16:57:48 +000010#if defined( Py_TRACE_REFS ) || defined( Py_REF_DEBUG )
Guido van Rossumbffd6832000-01-20 22:32:56 +000011DL_IMPORT(long) _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Guido van Rossum393661d2001-08-31 17:40:15 +000014DL_IMPORT(int) Py_DivisionWarningFlag;
15
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
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000095PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000096{
Guido van Rossumb18618d2000-05-03 23:44:39 +000097 if (op == NULL) {
98 PyErr_SetString(PyExc_SystemError,
99 "NULL object passed to PyObject_Init");
100 return op;
101 }
102 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000104 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105 return op;
106}
107
Guido van Rossumb18618d2000-05-03 23:44:39 +0000108PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000109PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000110{
111 if (op == NULL) {
112 PyErr_SetString(PyExc_SystemError,
113 "NULL object passed to PyObject_InitVar");
114 return op;
115 }
116 /* Any changes should be reflected in PyObject_INIT_VAR */
117 op->ob_size = size;
118 op->ob_type = tp;
119 _Py_NewReference((PyObject *)op);
120 return op;
121}
122
123PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000124_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000125{
126 PyObject *op;
127 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
128 if (op == NULL)
129 return PyErr_NoMemory();
130 return PyObject_INIT(op, tp);
131}
132
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000133PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000134_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000136 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000137 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000138 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000140 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000141 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000142}
143
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000144/* for binary compatibility with 2.2 */
145#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000146void
Fred Drake100814d2000-07-09 15:48:49 +0000147_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000148{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000149 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150}
151
Guido van Rossum90933611991-06-07 16:10:43 +0000152int
Fred Drake100814d2000-07-09 15:48:49 +0000153PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154{
Guido van Rossum278ef591991-07-27 21:40:24 +0000155 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000157 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000158#ifdef USE_STACKCHECK
159 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000160 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000161 return -1;
162 }
163#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000164 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000165 if (op == NULL) {
166 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 }
Guido van Rossum90933611991-06-07 16:10:43 +0000168 else {
169 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000170 fprintf(fp, "<refcnt %u at %p>",
171 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000172 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000173 PyObject *s;
174 if (flags & Py_PRINT_RAW)
175 s = PyObject_Str(op);
176 else
177 s = PyObject_Repr(op);
178 if (s == NULL)
179 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000180 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000181 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000182 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000183 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000184 }
Guido van Rossum90933611991-06-07 16:10:43 +0000185 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000186 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000187 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000188 if (ret == 0) {
189 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000191 clearerr(fp);
192 ret = -1;
193 }
194 }
195 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196}
197
Barry Warsaw9bf16442001-01-23 16:24:35 +0000198/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000199void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000200{
Barry Warsaweefb1072001-02-22 22:39:18 +0000201 if (op == NULL)
202 fprintf(stderr, "NULL\n");
203 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000204 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000205 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000206 fprintf(stderr, "\n"
207 "type : %s\n"
208 "refcount: %d\n"
209 "address : %p\n",
210 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
211 op->ob_refcnt,
212 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000213 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000214}
Barry Warsaw903138f2001-01-23 16:33:18 +0000215
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000216PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000217PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000219 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000220 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000221#ifdef USE_STACKCHECK
222 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000223 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000224 return NULL;
225 }
226#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000227 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000228 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000229 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000230 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000231 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000232 else {
233 PyObject *res;
234 res = (*v->ob_type->tp_repr)(v);
235 if (res == NULL)
236 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000237#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000238 if (PyUnicode_Check(res)) {
239 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000240 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000241 Py_DECREF(res);
242 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000243 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000244 else
245 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000246 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000247#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000248 if (!PyString_Check(res)) {
249 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000250 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000251 res->ob_type->tp_name);
252 Py_DECREF(res);
253 return NULL;
254 }
255 return res;
256 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000257}
258
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000259PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000260PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000261{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000262 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000263
Guido van Rossumc6004111993-11-05 10:22:19 +0000264 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000266 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000267 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000268 return v;
269 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000270 if (v->ob_type->tp_str == NULL)
271 return PyObject_Repr(v);
272
273 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000274 if (res == NULL)
275 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000276#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000277 if (PyUnicode_Check(res)) {
278 PyObject* str;
279 str = PyUnicode_AsEncodedString(res, NULL, NULL);
280 Py_DECREF(res);
281 if (str)
282 res = str;
283 else
284 return NULL;
285 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000286#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000287 if (!PyString_Check(res)) {
288 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000289 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000290 res->ob_type->tp_name);
291 Py_DECREF(res);
292 return NULL;
293 }
294 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000295}
296
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000297#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000298PyObject *
299PyObject_Unicode(PyObject *v)
300{
301 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000302
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000303 if (v == NULL)
304 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000305 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000306 Py_INCREF(v);
307 return v;
308 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000309 if (PyUnicode_Check(v)) {
310 /* For a Unicode subtype that's not a Unicode object,
311 return a true Unicode object with the same data. */
312 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
313 PyUnicode_GET_SIZE(v));
314 }
315 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000316 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000317 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000318 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000319 else {
320 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000321 static PyObject *unicodestr;
322 /* XXX As soon as we have a tp_unicode slot, we should
323 check this before trying the __unicode__
324 method. */
325 if (unicodestr == NULL) {
326 unicodestr= PyString_InternFromString(
327 "__unicode__");
328 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000329 return NULL;
330 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000331 func = PyObject_GetAttr(v, unicodestr);
332 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000333 res = PyEval_CallObject(func, (PyObject *)NULL);
334 Py_DECREF(func);
335 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000336 else {
337 PyErr_Clear();
338 if (v->ob_type->tp_str != NULL)
339 res = (*v->ob_type->tp_str)(v);
340 else
341 res = PyObject_Repr(v);
342 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000343 }
344 if (res == NULL)
345 return NULL;
346 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000347 PyObject *str;
348 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000349 Py_DECREF(res);
350 if (str)
351 res = str;
352 else
353 return NULL;
354 }
355 return res;
356}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000357#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000358
359
Guido van Rossuma4073002002-05-31 20:03:54 +0000360/* Helper to warn about deprecated tp_compare return values. Return:
361 -2 for an exception;
362 -1 if v < w;
363 0 if v == w;
364 1 if v > w.
365 (This function cannot return 2.)
366*/
367static int
368adjust_tp_compare(int c)
369{
370 if (PyErr_Occurred()) {
371 if (c != -1 && c != -2) {
372 PyObject *t, *v, *tb;
373 PyErr_Fetch(&t, &v, &tb);
374 if (PyErr_Warn(PyExc_RuntimeWarning,
375 "tp_compare didn't return -1 or -2 "
376 "for exception") < 0) {
377 Py_XDECREF(t);
378 Py_XDECREF(v);
379 Py_XDECREF(tb);
380 }
381 else
382 PyErr_Restore(t, v, tb);
383 }
384 return -2;
385 }
386 else if (c < -1 || c > 1) {
387 if (PyErr_Warn(PyExc_RuntimeWarning,
388 "tp_compare didn't return -1, 0 or 1") < 0)
389 return -2;
390 else
391 return c < -1 ? -1 : 1;
392 }
393 else {
394 assert(c >= -1 && c <= 1);
395 return c;
396 }
397}
398
399
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000400/* Macro to get the tp_richcompare field of a type if defined */
401#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
402 ? (t)->tp_richcompare : NULL)
403
Guido van Rossume797ec12001-01-17 15:24:28 +0000404/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
405static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000406
Guido van Rossume797ec12001-01-17 15:24:28 +0000407/* Try a genuine rich comparison, returning an object. Return:
408 NULL for exception;
409 NotImplemented if this particular rich comparison is not implemented or
410 undefined;
411 some object not equal to NotImplemented if it is implemented
412 (this latter object may not be a Boolean).
413*/
414static PyObject *
415try_rich_compare(PyObject *v, PyObject *w, int op)
416{
417 richcmpfunc f;
418 PyObject *res;
419
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000420 if (v->ob_type != w->ob_type &&
421 PyType_IsSubtype(w->ob_type, v->ob_type) &&
422 (f = RICHCOMPARE(w->ob_type)) != NULL) {
423 res = (*f)(w, v, swapped_op[op]);
424 if (res != Py_NotImplemented)
425 return res;
426 Py_DECREF(res);
427 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000428 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000429 res = (*f)(v, w, op);
430 if (res != Py_NotImplemented)
431 return res;
432 Py_DECREF(res);
433 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000434 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000435 return (*f)(w, v, swapped_op[op]);
436 }
437 res = Py_NotImplemented;
438 Py_INCREF(res);
439 return res;
440}
441
442/* Try a genuine rich comparison, returning an int. Return:
443 -1 for exception (including the case where try_rich_compare() returns an
444 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000445 0 if the outcome is false;
446 1 if the outcome is true;
447 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000448*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000449static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000450try_rich_compare_bool(PyObject *v, PyObject *w, int op)
451{
452 PyObject *res;
453 int ok;
454
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000455 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000456 return 2; /* Shortcut, avoid INCREF+DECREF */
457 res = try_rich_compare(v, w, op);
458 if (res == NULL)
459 return -1;
460 if (res == Py_NotImplemented) {
461 Py_DECREF(res);
462 return 2;
463 }
464 ok = PyObject_IsTrue(res);
465 Py_DECREF(res);
466 return ok;
467}
468
469/* Try rich comparisons to determine a 3-way comparison. Return:
470 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000471 -1 if v < w;
472 0 if v == w;
473 1 if v > w;
474 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000475*/
476static int
477try_rich_to_3way_compare(PyObject *v, PyObject *w)
478{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000479 static struct { int op; int outcome; } tries[3] = {
480 /* Try this operator, and if it is true, use this outcome: */
481 {Py_EQ, 0},
482 {Py_LT, -1},
483 {Py_GT, 1},
484 };
485 int i;
486
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000487 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000488 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000489
490 for (i = 0; i < 3; i++) {
491 switch (try_rich_compare_bool(v, w, tries[i].op)) {
492 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000493 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000494 case 1:
495 return tries[i].outcome;
496 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000497 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000498
499 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000500}
501
502/* Try a 3-way comparison, returning an int. Return:
503 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000504 -1 if v < w;
505 0 if v == w;
506 1 if v > w;
507 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000508*/
509static int
510try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000511{
512 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000513 cmpfunc f;
514
515 /* Comparisons involving instances are given to instance_compare,
516 which has the same return conventions as this function. */
517
Guido van Rossumab3b0342001-09-18 20:38:53 +0000518 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000519 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000520 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000521 if (PyInstance_Check(w))
522 return (*w->ob_type->tp_compare)(v, w);
523
Guido van Rossumab3b0342001-09-18 20:38:53 +0000524 /* If both have the same (non-NULL) tp_compare, use it. */
525 if (f != NULL && f == w->ob_type->tp_compare) {
526 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000527 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000528 }
529
530 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
531 if (f == _PyObject_SlotCompare ||
532 w->ob_type->tp_compare == _PyObject_SlotCompare)
533 return _PyObject_SlotCompare(v, w);
534
Guido van Rossume797ec12001-01-17 15:24:28 +0000535 /* Try coercion; if it fails, give up */
536 c = PyNumber_CoerceEx(&v, &w);
537 if (c < 0)
538 return -2;
539 if (c > 0)
540 return 2;
541
542 /* Try v's comparison, if defined */
543 if ((f = v->ob_type->tp_compare) != NULL) {
544 c = (*f)(v, w);
545 Py_DECREF(v);
546 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000547 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000548 }
549
550 /* Try w's comparison, if defined */
551 if ((f = w->ob_type->tp_compare) != NULL) {
552 c = (*f)(w, v); /* swapped! */
553 Py_DECREF(v);
554 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000555 c = adjust_tp_compare(c);
556 if (c >= -1)
557 return -c; /* Swapped! */
558 else
559 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000560 }
561
562 /* No comparison defined */
563 Py_DECREF(v);
564 Py_DECREF(w);
565 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000566}
567
Guido van Rossume797ec12001-01-17 15:24:28 +0000568/* Final fallback 3-way comparison, returning an int. Return:
569 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000570 -1 if v < w;
571 0 if v == w;
572 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000573*/
574static int
575default_3way_compare(PyObject *v, PyObject *w)
576{
577 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000578 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000579
580 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000581 /* When comparing these pointers, they must be cast to
582 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
583 * uintptr_t). ANSI specifies that pointer compares other
584 * than == and != to non-related structures are undefined.
585 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000586 Py_uintptr_t vv = (Py_uintptr_t)v;
587 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000588 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
589 }
590
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000591#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000592 /* Special case for Unicode */
593 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
594 c = PyUnicode_Compare(v, w);
595 if (!PyErr_Occurred())
596 return c;
597 /* TypeErrors are ignored: if Unicode coercion fails due
598 to one of the arguments not having the right type, we
599 continue as defined by the coercion protocol (see
600 above). Luckily, decoding errors are reported as
601 ValueErrors and are not masked by this technique. */
602 if (!PyErr_ExceptionMatches(PyExc_TypeError))
603 return -2;
604 PyErr_Clear();
605 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000606#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000607
Guido van Rossum0871e932001-01-22 19:28:09 +0000608 /* None is smaller than anything */
609 if (v == Py_None)
610 return -1;
611 if (w == Py_None)
612 return 1;
613
Guido van Rossume797ec12001-01-17 15:24:28 +0000614 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000615 if (v->ob_type->tp_as_number)
616 vname = "";
617 else
618 vname = v->ob_type->tp_name;
619 if (w->ob_type->tp_as_number)
620 wname = "";
621 else
622 wname = w->ob_type->tp_name;
623 c = strcmp(vname, wname);
624 if (c < 0)
625 return -1;
626 if (c > 0)
627 return 1;
628 /* Same type name, or (more likely) incomparable numeric types */
629 return ((Py_uintptr_t)(v->ob_type) < (
630 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000631}
632
633#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
634
Tim Peters6d60b2e2001-05-07 20:53:51 +0000635/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000636 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000637 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000638 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000639 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000640 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000641 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000642*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000643static int
Fred Drake100814d2000-07-09 15:48:49 +0000644do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000645{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000646 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000647 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000648
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000649 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000650 && (f = v->ob_type->tp_compare) != NULL) {
651 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000652 if (PyInstance_Check(v)) {
653 /* Instance tp_compare has a different signature.
654 But if it returns undefined we fall through. */
655 if (c != 2)
656 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000657 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000658 }
659 else
660 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000661 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000662 /* We only get here if one of the following is true:
663 a) v and w have different types
664 b) v and w have the same type, which doesn't have tp_compare
665 c) v and w are instances, and either __cmp__ is not defined or
666 __cmp__ returns NotImplemented
667 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000668 c = try_rich_to_3way_compare(v, w);
669 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000670 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000671 c = try_3way_compare(v, w);
672 if (c < 2)
673 return c;
674 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000675}
676
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000677/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000678 some types) and decremented on exit. If the count exceeds the
679 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000680
681 This is a tunable parameter that should only affect the performance
682 of comparisons, nothing else. Setting it high makes comparing deeply
683 nested non-cyclical data structures faster, but makes comparing cyclical
684 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000685*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000686#define NESTING_LIMIT 20
687
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000688static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000689
690static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000691get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000692{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000693 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000694 PyObject *tstate_dict, *inprogress;
695
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000696 if (key == NULL) {
697 key = PyString_InternFromString("cmp_state");
698 if (key == NULL)
699 return NULL;
700 }
701
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000702 tstate_dict = PyThreadState_GetDict();
703 if (tstate_dict == NULL) {
704 PyErr_BadInternalCall();
705 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000706 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000707
Tim Peters803526b2002-07-07 05:13:56 +0000708 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000709 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000710 inprogress = PyDict_New();
711 if (inprogress == NULL)
712 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000713 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000714 Py_DECREF(inprogress);
715 return NULL;
716 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000717 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000718 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000719
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000720 return inprogress;
721}
722
723static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000724check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000725{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000726 PyObject *inprogress;
727 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000728 Py_uintptr_t iv = (Py_uintptr_t)v;
729 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000730 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000731
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000732 inprogress = get_inprogress_dict();
733 if (inprogress == NULL)
734 return NULL;
735
736 token = PyTuple_New(3);
737 if (token == NULL)
738 return NULL;
739
740 if (iv <= iw) {
741 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
742 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
743 if (op >= 0)
744 op = swapped_op[op];
745 } else {
746 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
747 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
748 }
749 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
750 if (x == NULL || y == NULL || z == NULL) {
751 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000752 return NULL;
753 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000754
755 if (PyDict_GetItem(inprogress, token) != NULL) {
756 Py_DECREF(token);
757 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000758 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000759
760 if (PyDict_SetItem(inprogress, token, token) < 0) {
761 Py_DECREF(token);
762 return NULL;
763 }
764
765 return token;
766}
767
768static void
769delete_token(PyObject *token)
770{
771 PyObject *inprogress;
772
773 if (token == NULL || token == Py_None)
774 return;
775 inprogress = get_inprogress_dict();
776 if (inprogress == NULL)
777 PyErr_Clear();
778 else
779 PyDict_DelItem(inprogress, token);
780 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000781}
782
Tim Petersc99213f2001-11-04 05:57:16 +0000783/* Compare v to w. Return
784 -1 if v < w or exception (PyErr_Occurred() true in latter case).
785 0 if v == w.
786 1 if v > w.
787 XXX The docs (C API manual) say the return value is undefined in case
788 XXX of error.
789*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000790int
Fred Drake100814d2000-07-09 15:48:49 +0000791PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000793 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000794 int result;
795
Jack Jansend49cbe12000-08-22 21:52:51 +0000796#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000797 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000798 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000799 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000800 }
801#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000802 if (v == NULL || w == NULL) {
803 PyErr_BadInternalCall();
804 return -1;
805 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000806 if (v == w)
807 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000808 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000809 compare_nesting++;
810 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000811 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000812 || (vtp->tp_as_sequence
813 && !PyString_Check(v)
814 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000815 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000816 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000817
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000818 if (token == NULL) {
819 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000820 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000821 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000822 /* already comparing these objects. assume
823 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000824 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000825 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000826 else {
827 result = do_cmp(v, w);
828 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000829 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000830 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000831 else {
832 result = do_cmp(v, w);
833 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000834 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000835 return result < 0 ? -1 : result;
836}
837
Tim Petersc99213f2001-11-04 05:57:16 +0000838/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000839static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000840convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000841{
Guido van Rossume797ec12001-01-17 15:24:28 +0000842 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000843 switch (op) {
844 case Py_LT: c = c < 0; break;
845 case Py_LE: c = c <= 0; break;
846 case Py_EQ: c = c == 0; break;
847 case Py_NE: c = c != 0; break;
848 case Py_GT: c = c > 0; break;
849 case Py_GE: c = c >= 0; break;
850 }
851 result = c ? Py_True : Py_False;
852 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000853 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000854}
Tim Peters803526b2002-07-07 05:13:56 +0000855
Tim Petersc99213f2001-11-04 05:57:16 +0000856/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
857 Return
858 NULL if error
859 Py_True if v op w
860 Py_False if not (v op w)
861*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000862static PyObject *
863try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
864{
865 int c;
866
867 c = try_3way_compare(v, w);
868 if (c >= 2)
869 c = default_3way_compare(v, w);
870 if (c <= -2)
871 return NULL;
872 return convert_3way_to_object(op, c);
873}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000874
Tim Petersc99213f2001-11-04 05:57:16 +0000875/* Do rich comparison on v and w. Return
876 NULL if error
877 Else a new reference to an object other than Py_NotImplemented, usually(?):
878 Py_True if v op w
879 Py_False if not (v op w)
880*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000881static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000882do_richcmp(PyObject *v, PyObject *w, int op)
883{
884 PyObject *res;
885
886 res = try_rich_compare(v, w, op);
887 if (res != Py_NotImplemented)
888 return res;
889 Py_DECREF(res);
890
891 return try_3way_to_rich_compare(v, w, op);
892}
893
Tim Petersc99213f2001-11-04 05:57:16 +0000894/* Return:
895 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000896 some object not equal to NotImplemented if it is implemented
897 (this latter object may not be a Boolean).
898*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000899PyObject *
900PyObject_RichCompare(PyObject *v, PyObject *w, int op)
901{
902 PyObject *res;
903
904 assert(Py_LT <= op && op <= Py_GE);
905
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000906 compare_nesting++;
907 if (compare_nesting > NESTING_LIMIT &&
908 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000909 || (v->ob_type->tp_as_sequence
910 && !PyString_Check(v)
911 && !PyTuple_Check(v)))) {
Tim Peters67754e92001-11-04 07:29:31 +0000912
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000913 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000914 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000915 if (token == NULL) {
916 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000917 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000918 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000919 else if (token == Py_None) {
920 /* already comparing these objects with this operator.
921 assume they're equal until shown otherwise */
922 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000923 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000924 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000925 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000926 else {
927 PyErr_SetString(PyExc_ValueError,
928 "can't order recursive values");
929 res = NULL;
930 }
931 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000932 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000933 else {
934 res = do_richcmp(v, w, op);
935 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000936 }
Tim Peters67754e92001-11-04 07:29:31 +0000937 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000938 }
Tim Peters67754e92001-11-04 07:29:31 +0000939
940 /* No nesting extremism.
941 If the types are equal, and not old-style instances, try to
942 get out cheap (don't bother with coercions etc.). */
943 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
944 cmpfunc fcmp;
945 richcmpfunc frich = RICHCOMPARE(v->ob_type);
946 /* If the type has richcmp, try it first. try_rich_compare
947 tries it two-sided, which is not needed since we've a
948 single type only. */
949 if (frich != NULL) {
950 res = (*frich)(v, w, op);
951 if (res != Py_NotImplemented)
952 goto Done;
953 Py_DECREF(res);
954 }
955 /* No richcmp, or this particular richmp not implemented.
956 Try 3-way cmp. */
957 fcmp = v->ob_type->tp_compare;
958 if (fcmp != NULL) {
959 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000960 c = adjust_tp_compare(c);
961 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000962 res = NULL;
963 goto Done;
964 }
965 res = convert_3way_to_object(op, c);
966 goto Done;
967 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000968 }
Tim Peters67754e92001-11-04 07:29:31 +0000969
970 /* Fast path not taken, or couldn't deliver a useful result. */
971 res = do_richcmp(v, w, op);
972Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000973 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000974 return res;
975}
976
Tim Petersde9725f2001-05-05 10:06:17 +0000977/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000978int
979PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
980{
981 PyObject *res = PyObject_RichCompare(v, w, op);
982 int ok;
983
984 if (res == NULL)
985 return -1;
986 ok = PyObject_IsTrue(res);
987 Py_DECREF(res);
988 return ok;
989}
Fred Drake13634cf2000-06-29 19:17:04 +0000990
991/* Set of hash utility functions to help maintaining the invariant that
992 iff a==b then hash(a)==hash(b)
993
994 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
995*/
996
997long
Fred Drake100814d2000-07-09 15:48:49 +0000998_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000999{
Tim Peters39dce292000-08-15 03:34:48 +00001000 double intpart, fractpart;
1001 int expo;
1002 long hipart;
1003 long x; /* the final hash value */
1004 /* This is designed so that Python numbers of different types
1005 * that compare equal hash to the same value; otherwise comparisons
1006 * of mapping keys will turn out weird.
1007 */
1008
1009#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1010{
1011 extended e;
1012 fractpart = modf(v, &e);
1013 intpart = e;
1014}
1015#else
1016 fractpart = modf(v, &intpart);
1017#endif
1018 if (fractpart == 0.0) {
1019 /* This must return the same hash as an equal int or long. */
1020 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1021 /* Convert to long and use its hash. */
1022 PyObject *plong; /* converted to Python long */
1023 if (Py_IS_INFINITY(intpart))
1024 /* can't convert to long int -- arbitrary */
1025 v = v < 0 ? -271828.0 : 314159.0;
1026 plong = PyLong_FromDouble(v);
1027 if (plong == NULL)
1028 return -1;
1029 x = PyObject_Hash(plong);
1030 Py_DECREF(plong);
1031 return x;
1032 }
1033 /* Fits in a C long == a Python int, so is its own hash. */
1034 x = (long)intpart;
1035 if (x == -1)
1036 x = -2;
1037 return x;
1038 }
1039 /* The fractional part is non-zero, so we don't have to worry about
1040 * making this match the hash of some other type.
1041 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001042 * Since the VAX D double format has 56 mantissa bits, which is the
1043 * most of any double format in use, each of these parts may have as
1044 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001045 * So, assuming sizeof(long) >= 4, each part can be broken into two
1046 * longs; frexp and multiplication are used to do that.
1047 * Also, since the Cray double format has 15 exponent bits, which is
1048 * the most of any double format in use, shifting the exponent field
1049 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001050 */
Tim Peters39dce292000-08-15 03:34:48 +00001051 v = frexp(v, &expo);
1052 v *= 2147483648.0; /* 2**31 */
1053 hipart = (long)v; /* take the top 32 bits */
1054 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1055 x = hipart + (long)v + (expo << 15);
1056 if (x == -1)
1057 x = -2;
1058 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001059}
1060
1061long
Fred Drake100814d2000-07-09 15:48:49 +00001062_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001063{
1064#if SIZEOF_LONG >= SIZEOF_VOID_P
1065 return (long)p;
1066#else
1067 /* convert to a Python long and hash that */
1068 PyObject* longobj;
1069 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001070
Fred Drake13634cf2000-06-29 19:17:04 +00001071 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1072 x = -1;
1073 goto finally;
1074 }
1075 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001076
Fred Drake13634cf2000-06-29 19:17:04 +00001077finally:
1078 Py_XDECREF(longobj);
1079 return x;
1080#endif
1081}
1082
1083
Guido van Rossum9bfef441993-03-29 10:43:31 +00001084long
Fred Drake100814d2000-07-09 15:48:49 +00001085PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001086{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001087 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001088 if (tp->tp_hash != NULL)
1089 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001090 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001091 return _Py_HashPointer(v); /* Use address as hash value */
1092 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001093 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001094 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001095 return -1;
1096}
1097
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001098PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001099PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001100{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001102
Tim Peters6d6c1a32001-08-02 04:15:00 +00001103 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001104 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001105 w = PyString_InternFromString(name);
1106 if (w == NULL)
1107 return NULL;
1108 res = PyObject_GetAttr(v, w);
1109 Py_XDECREF(w);
1110 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001111}
1112
1113int
Fred Drake100814d2000-07-09 15:48:49 +00001114PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001115{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001116 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001117 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001118 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001119 return 1;
1120 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001121 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001122 return 0;
1123}
1124
1125int
Fred Drake100814d2000-07-09 15:48:49 +00001126PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001127{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 PyObject *s;
1129 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001130
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001132 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001133 s = PyString_InternFromString(name);
1134 if (s == NULL)
1135 return -1;
1136 res = PyObject_SetAttr(v, s, w);
1137 Py_XDECREF(s);
1138 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001139}
1140
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001141PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001142PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001143{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144 PyTypeObject *tp = v->ob_type;
1145
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001146 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001147#ifdef Py_USING_UNICODE
1148 /* The Unicode to string conversion is done here because the
1149 existing tp_getattro slots expect a string object as name
1150 and we wouldn't want to break those. */
1151 if (PyUnicode_Check(name)) {
1152 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1153 if (name == NULL)
1154 return NULL;
1155 }
1156 else
1157#endif
1158 {
1159 PyErr_SetString(PyExc_TypeError,
1160 "attribute name must be string");
1161 return NULL;
1162 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001163 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 if (tp->tp_getattro != NULL)
1165 return (*tp->tp_getattro)(v, name);
1166 if (tp->tp_getattr != NULL)
1167 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1168 PyErr_Format(PyExc_AttributeError,
1169 "'%.50s' object has no attribute '%.400s'",
1170 tp->tp_name, PyString_AS_STRING(name));
1171 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001172}
1173
1174int
Fred Drake100814d2000-07-09 15:48:49 +00001175PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001176{
1177 PyObject *res = PyObject_GetAttr(v, name);
1178 if (res != NULL) {
1179 Py_DECREF(res);
1180 return 1;
1181 }
1182 PyErr_Clear();
1183 return 0;
1184}
1185
1186int
Fred Drake100814d2000-07-09 15:48:49 +00001187PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001188{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001190 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001191
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001192 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001193#ifdef Py_USING_UNICODE
1194 /* The Unicode to string conversion is done here because the
1195 existing tp_setattro slots expect a string object as name
1196 and we wouldn't want to break those. */
1197 if (PyUnicode_Check(name)) {
1198 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1199 if (name == NULL)
1200 return -1;
1201 }
Tim Peters803526b2002-07-07 05:13:56 +00001202 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001203#endif
1204 {
1205 PyErr_SetString(PyExc_TypeError,
1206 "attribute name must be string");
1207 return -1;
1208 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001209 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 else
1211 Py_INCREF(name);
1212
1213 PyString_InternInPlace(&name);
1214 if (tp->tp_setattro != NULL) {
1215 err = (*tp->tp_setattro)(v, name, value);
1216 Py_DECREF(name);
1217 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001218 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001219 if (tp->tp_setattr != NULL) {
1220 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1221 Py_DECREF(name);
1222 return err;
1223 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001224 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1226 PyErr_Format(PyExc_TypeError,
1227 "'%.100s' object has no attributes "
1228 "(%s .%.100s)",
1229 tp->tp_name,
1230 value==NULL ? "del" : "assign to",
1231 PyString_AS_STRING(name));
1232 else
1233 PyErr_Format(PyExc_TypeError,
1234 "'%.100s' object has only read-only attributes "
1235 "(%s .%.100s)",
1236 tp->tp_name,
1237 value==NULL ? "del" : "assign to",
1238 PyString_AS_STRING(name));
1239 return -1;
1240}
1241
1242/* Helper to get a pointer to an object's __dict__ slot, if any */
1243
1244PyObject **
1245_PyObject_GetDictPtr(PyObject *obj)
1246{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001247 long dictoffset;
1248 PyTypeObject *tp = obj->ob_type;
1249
1250 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1251 return NULL;
1252 dictoffset = tp->tp_dictoffset;
1253 if (dictoffset == 0)
1254 return NULL;
1255 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001256 int tsize;
1257 size_t size;
1258
1259 tsize = ((PyVarObject *)obj)->ob_size;
1260 if (tsize < 0)
1261 tsize = -tsize;
1262 size = _PyObject_VAR_SIZE(tp, tsize);
1263
Tim Peters6d483d32001-10-06 21:27:34 +00001264 dictoffset += (long)size;
1265 assert(dictoffset > 0);
1266 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001267 }
1268 return (PyObject **) ((char *)obj + dictoffset);
1269}
1270
1271/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1272
1273PyObject *
1274PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1275{
1276 PyTypeObject *tp = obj->ob_type;
1277 PyObject *descr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001278 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001279 descrgetfunc f;
1280 PyObject **dictptr;
1281
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001282 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001283#ifdef Py_USING_UNICODE
1284 /* The Unicode to string conversion is done here because the
1285 existing tp_setattro slots expect a string object as name
1286 and we wouldn't want to break those. */
1287 if (PyUnicode_Check(name)) {
1288 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1289 if (name == NULL)
1290 return NULL;
1291 }
Tim Peters803526b2002-07-07 05:13:56 +00001292 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001293#endif
1294 {
1295 PyErr_SetString(PyExc_TypeError,
1296 "attribute name must be string");
1297 return NULL;
1298 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001299 }
1300 else
1301 Py_INCREF(name);
1302
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001304 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001305 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 }
1307
1308 descr = _PyType_Lookup(tp, name);
1309 f = NULL;
1310 if (descr != NULL) {
1311 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001312 if (f != NULL && PyDescr_IsData(descr)) {
1313 res = f(descr, obj, (PyObject *)obj->ob_type);
1314 goto done;
1315 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316 }
1317
1318 dictptr = _PyObject_GetDictPtr(obj);
1319 if (dictptr != NULL) {
1320 PyObject *dict = *dictptr;
1321 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001322 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323 if (res != NULL) {
1324 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001325 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326 }
1327 }
1328 }
1329
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001330 if (f != NULL) {
1331 res = f(descr, obj, (PyObject *)obj->ob_type);
1332 goto done;
1333 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334
1335 if (descr != NULL) {
1336 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001337 res = descr;
1338 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 }
1340
1341 PyErr_Format(PyExc_AttributeError,
1342 "'%.50s' object has no attribute '%.400s'",
1343 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001344 done:
1345 Py_DECREF(name);
1346 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001347}
1348
1349int
1350PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1351{
1352 PyTypeObject *tp = obj->ob_type;
1353 PyObject *descr;
1354 descrsetfunc f;
1355 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001356 int res = -1;
1357
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001358 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001359#ifdef Py_USING_UNICODE
1360 /* The Unicode to string conversion is done here because the
1361 existing tp_setattro slots expect a string object as name
1362 and we wouldn't want to break those. */
1363 if (PyUnicode_Check(name)) {
1364 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1365 if (name == NULL)
1366 return -1;
1367 }
Tim Peters803526b2002-07-07 05:13:56 +00001368 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001369#endif
1370 {
1371 PyErr_SetString(PyExc_TypeError,
1372 "attribute name must be string");
1373 return -1;
1374 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001375 }
1376 else
1377 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001378
1379 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001380 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001381 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001382 }
1383
1384 descr = _PyType_Lookup(tp, name);
1385 f = NULL;
1386 if (descr != NULL) {
1387 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001388 if (f != NULL && PyDescr_IsData(descr)) {
1389 res = f(descr, obj, value);
1390 goto done;
1391 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392 }
1393
1394 dictptr = _PyObject_GetDictPtr(obj);
1395 if (dictptr != NULL) {
1396 PyObject *dict = *dictptr;
1397 if (dict == NULL && value != NULL) {
1398 dict = PyDict_New();
1399 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001400 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401 *dictptr = dict;
1402 }
1403 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001404 if (value == NULL)
1405 res = PyDict_DelItem(dict, name);
1406 else
1407 res = PyDict_SetItem(dict, name, value);
1408 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1409 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001410 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001411 }
1412 }
1413
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001414 if (f != NULL) {
1415 res = f(descr, obj, value);
1416 goto done;
1417 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001418
1419 if (descr == NULL) {
1420 PyErr_Format(PyExc_AttributeError,
1421 "'%.50s' object has no attribute '%.400s'",
1422 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001423 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 }
1425
1426 PyErr_Format(PyExc_AttributeError,
1427 "'%.50s' object attribute '%.400s' is read-only",
1428 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001429 done:
1430 Py_DECREF(name);
1431 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001432}
1433
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001434/* Test a value used as condition, e.g., in a for or if statement.
1435 Return -1 if an error occurred */
1436
1437int
Fred Drake100814d2000-07-09 15:48:49 +00001438PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001439{
1440 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001442 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001443 else if (v->ob_type->tp_as_number != NULL &&
1444 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001445 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001446 else if (v->ob_type->tp_as_mapping != NULL &&
1447 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001448 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001449 else if (v->ob_type->tp_as_sequence != NULL &&
1450 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001451 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1452 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001453 return 1;
1454 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001455}
1456
Tim Peters803526b2002-07-07 05:13:56 +00001457/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001458 Return -1 if an error occurred */
1459
1460int
Fred Drake100814d2000-07-09 15:48:49 +00001461PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001462{
1463 int res;
1464 res = PyObject_IsTrue(v);
1465 if (res < 0)
1466 return res;
1467 return res == 0;
1468}
1469
Guido van Rossum5524a591995-01-10 15:26:20 +00001470/* Coerce two numeric types to the "larger" one.
1471 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001472 Return value:
1473 -1 if an error occurred;
1474 0 if the coercion succeeded (and then the reference counts are increased);
1475 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001476*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001477int
Fred Drake100814d2000-07-09 15:48:49 +00001478PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001479{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001480 register PyObject *v = *pv;
1481 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001482 int res;
1483
Guido van Rossum517c7d42002-04-26 02:49:14 +00001484 /* Shortcut only for old-style types */
1485 if (v->ob_type == w->ob_type &&
1486 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1487 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001488 Py_INCREF(v);
1489 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001490 return 0;
1491 }
1492 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1493 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1494 if (res <= 0)
1495 return res;
1496 }
1497 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1498 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1499 if (res <= 0)
1500 return res;
1501 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001502 return 1;
1503}
1504
Guido van Rossume797ec12001-01-17 15:24:28 +00001505/* Coerce two numeric types to the "larger" one.
1506 Increment the reference count on each argument.
1507 Return -1 and raise an exception if no coercion is possible
1508 (and then no reference count is incremented).
1509*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001510int
Fred Drake100814d2000-07-09 15:48:49 +00001511PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001512{
1513 int err = PyNumber_CoerceEx(pv, pw);
1514 if (err <= 0)
1515 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001516 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001517 return -1;
1518}
1519
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001520
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001521/* Test whether an object can be called */
1522
1523int
Fred Drake100814d2000-07-09 15:48:49 +00001524PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001525{
1526 if (x == NULL)
1527 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001528 if (PyInstance_Check(x)) {
1529 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001530 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001531 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001532 return 0;
1533 }
1534 /* Could test recursively but don't, for fear of endless
1535 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001536 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001537 return 1;
1538 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001539 else {
1540 return x->ob_type->tp_call != NULL;
1541 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001542}
1543
Tim Peters7eea37e2001-09-04 22:08:56 +00001544/* Helper for PyObject_Dir.
1545 Merge the __dict__ of aclass into dict, and recursively also all
1546 the __dict__s of aclass's base classes. The order of merging isn't
1547 defined, as it's expected that only the final set of dict keys is
1548 interesting.
1549 Return 0 on success, -1 on error.
1550*/
1551
1552static int
1553merge_class_dict(PyObject* dict, PyObject* aclass)
1554{
1555 PyObject *classdict;
1556 PyObject *bases;
1557
1558 assert(PyDict_Check(dict));
1559 assert(aclass);
1560
1561 /* Merge in the type's dict (if any). */
1562 classdict = PyObject_GetAttrString(aclass, "__dict__");
1563 if (classdict == NULL)
1564 PyErr_Clear();
1565 else {
1566 int status = PyDict_Update(dict, classdict);
1567 Py_DECREF(classdict);
1568 if (status < 0)
1569 return -1;
1570 }
1571
1572 /* Recursively merge in the base types' (if any) dicts. */
1573 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001574 if (bases == NULL)
1575 PyErr_Clear();
1576 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001577 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001578 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001579 n = PySequence_Size(bases); /* This better be right */
1580 if (n < 0)
1581 PyErr_Clear();
1582 else {
1583 for (i = 0; i < n; i++) {
1584 PyObject *base = PySequence_GetItem(bases, i);
1585 if (base == NULL) {
1586 Py_DECREF(bases);
1587 return -1;
1588 }
1589 if (merge_class_dict(dict, base) < 0) {
1590 Py_DECREF(bases);
1591 return -1;
1592 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001593 }
1594 }
1595 Py_DECREF(bases);
1596 }
1597 return 0;
1598}
1599
Tim Peters305b5852001-09-17 02:38:46 +00001600/* Helper for PyObject_Dir.
1601 If obj has an attr named attrname that's a list, merge its string
1602 elements into keys of dict.
1603 Return 0 on success, -1 on error. Errors due to not finding the attr,
1604 or the attr not being a list, are suppressed.
1605*/
1606
1607static int
1608merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1609{
1610 PyObject *list;
1611 int result = 0;
1612
1613 assert(PyDict_Check(dict));
1614 assert(obj);
1615 assert(attrname);
1616
1617 list = PyObject_GetAttrString(obj, attrname);
1618 if (list == NULL)
1619 PyErr_Clear();
1620
1621 else if (PyList_Check(list)) {
1622 int i;
1623 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1624 PyObject *item = PyList_GET_ITEM(list, i);
1625 if (PyString_Check(item)) {
1626 result = PyDict_SetItem(dict, item, Py_None);
1627 if (result < 0)
1628 break;
1629 }
1630 }
1631 }
1632
1633 Py_XDECREF(list);
1634 return result;
1635}
1636
Tim Peters7eea37e2001-09-04 22:08:56 +00001637/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1638 docstring, which should be kept in synch with this implementation. */
1639
1640PyObject *
1641PyObject_Dir(PyObject *arg)
1642{
1643 /* Set exactly one of these non-NULL before the end. */
1644 PyObject *result = NULL; /* result list */
1645 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1646
1647 /* If NULL arg, return the locals. */
1648 if (arg == NULL) {
1649 PyObject *locals = PyEval_GetLocals();
1650 if (locals == NULL)
1651 goto error;
1652 result = PyDict_Keys(locals);
1653 if (result == NULL)
1654 goto error;
1655 }
1656
1657 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001658 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001659 masterdict = PyObject_GetAttrString(arg, "__dict__");
1660 if (masterdict == NULL)
1661 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001662 if (!PyDict_Check(masterdict)) {
1663 PyErr_SetString(PyExc_TypeError,
1664 "module.__dict__ is not a dictionary");
1665 goto error;
1666 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001667 }
1668
1669 /* Elif some form of type or class, grab its dict and its bases.
1670 We deliberately don't suck up its __class__, as methods belonging
1671 to the metaclass would probably be more confusing than helpful. */
1672 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1673 masterdict = PyDict_New();
1674 if (masterdict == NULL)
1675 goto error;
1676 if (merge_class_dict(masterdict, arg) < 0)
1677 goto error;
1678 }
1679
1680 /* Else look at its dict, and the attrs reachable from its class. */
1681 else {
1682 PyObject *itsclass;
1683 /* Create a dict to start with. CAUTION: Not everything
1684 responding to __dict__ returns a dict! */
1685 masterdict = PyObject_GetAttrString(arg, "__dict__");
1686 if (masterdict == NULL) {
1687 PyErr_Clear();
1688 masterdict = PyDict_New();
1689 }
1690 else if (!PyDict_Check(masterdict)) {
1691 Py_DECREF(masterdict);
1692 masterdict = PyDict_New();
1693 }
1694 else {
1695 /* The object may have returned a reference to its
1696 dict, so copy it to avoid mutating it. */
1697 PyObject *temp = PyDict_Copy(masterdict);
1698 Py_DECREF(masterdict);
1699 masterdict = temp;
1700 }
1701 if (masterdict == NULL)
1702 goto error;
1703
Tim Peters305b5852001-09-17 02:38:46 +00001704 /* Merge in __members__ and __methods__ (if any).
1705 XXX Would like this to go away someday; for now, it's
1706 XXX needed to get at im_self etc of method objects. */
1707 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1708 goto error;
1709 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1710 goto error;
1711
Tim Peters7eea37e2001-09-04 22:08:56 +00001712 /* Merge in attrs reachable from its class.
1713 CAUTION: Not all objects have a __class__ attr. */
1714 itsclass = PyObject_GetAttrString(arg, "__class__");
1715 if (itsclass == NULL)
1716 PyErr_Clear();
1717 else {
1718 int status = merge_class_dict(masterdict, itsclass);
1719 Py_DECREF(itsclass);
1720 if (status < 0)
1721 goto error;
1722 }
1723 }
1724
1725 assert((result == NULL) ^ (masterdict == NULL));
1726 if (masterdict != NULL) {
1727 /* The result comes from its keys. */
1728 assert(result == NULL);
1729 result = PyDict_Keys(masterdict);
1730 if (result == NULL)
1731 goto error;
1732 }
1733
1734 assert(result);
1735 if (PyList_Sort(result) != 0)
1736 goto error;
1737 else
1738 goto normal_return;
1739
1740 error:
1741 Py_XDECREF(result);
1742 result = NULL;
1743 /* fall through */
1744 normal_return:
1745 Py_XDECREF(masterdict);
1746 return result;
1747}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001748
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001749/*
1750NoObject is usable as a non-NULL undefined value, used by the macro None.
1751There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001752so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001753(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001754*/
1755
Guido van Rossum0c182a11992-03-27 17:26:13 +00001756/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001757static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001758none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001759{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001760 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001761}
1762
Barry Warsaw9bf16442001-01-23 16:24:35 +00001763/* ARGUSED */
1764static void
Tim Peters803526b2002-07-07 05:13:56 +00001765none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001766{
1767 /* This should never get called, but we also don't want to SEGV if
1768 * we accidently decref None out of existance.
1769 */
1770 abort();
1771}
1772
1773
Guido van Rossumba21a492001-08-16 08:17:26 +00001774static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001775 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001776 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001777 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001778 0,
1779 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001780 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001781 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001782 0, /*tp_getattr*/
1783 0, /*tp_setattr*/
1784 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001785 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001786 0, /*tp_as_number*/
1787 0, /*tp_as_sequence*/
1788 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001789 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001790};
1791
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001792PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001793 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001794};
1795
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001796/* NotImplemented is an object that can be used to signal that an
1797 operation is not implemented for the given type combination. */
1798
1799static PyObject *
1800NotImplemented_repr(PyObject *op)
1801{
1802 return PyString_FromString("NotImplemented");
1803}
1804
1805static PyTypeObject PyNotImplemented_Type = {
1806 PyObject_HEAD_INIT(&PyType_Type)
1807 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001808 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001809 0,
1810 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001811 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001812 0, /*tp_print*/
1813 0, /*tp_getattr*/
1814 0, /*tp_setattr*/
1815 0, /*tp_compare*/
1816 (reprfunc)NotImplemented_repr, /*tp_repr*/
1817 0, /*tp_as_number*/
1818 0, /*tp_as_sequence*/
1819 0, /*tp_as_mapping*/
1820 0, /*tp_hash */
1821};
1822
1823PyObject _Py_NotImplementedStruct = {
1824 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1825};
1826
Guido van Rossumba21a492001-08-16 08:17:26 +00001827void
1828_Py_ReadyTypes(void)
1829{
1830 if (PyType_Ready(&PyType_Type) < 0)
1831 Py_FatalError("Can't initialize 'type'");
1832
Guido van Rossum77f6a652002-04-03 22:41:51 +00001833 if (PyType_Ready(&PyBool_Type) < 0)
1834 Py_FatalError("Can't initialize 'bool'");
1835
Guido van Rossumcacfc072002-05-24 19:01:59 +00001836 if (PyType_Ready(&PyString_Type) < 0)
1837 Py_FatalError("Can't initialize 'str'");
1838
Guido van Rossumba21a492001-08-16 08:17:26 +00001839 if (PyType_Ready(&PyList_Type) < 0)
1840 Py_FatalError("Can't initialize 'list'");
1841
1842 if (PyType_Ready(&PyNone_Type) < 0)
1843 Py_FatalError("Can't initialize type(None)");
1844
1845 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1846 Py_FatalError("Can't initialize type(NotImplemented)");
1847}
1848
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849
Guido van Rossum84a90321996-05-22 16:34:47 +00001850#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001854void
Fred Drake100814d2000-07-09 15:48:49 +00001855_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001856{
1857 refchain._ob_prev = refchain._ob_next = &refchain;
1858 _Py_RefTotal = 0;
1859}
1860
1861void
Fred Drake100814d2000-07-09 15:48:49 +00001862_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001863{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001864 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001865 op->ob_refcnt = 1;
1866 op->_ob_next = refchain._ob_next;
1867 op->_ob_prev = &refchain;
1868 refchain._ob_next->_ob_prev = op;
1869 refchain._ob_next = op;
Tim Peters4be93d02002-07-07 19:59:50 +00001870 _PyMAYBE_BUMP_COUNT(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001871}
1872
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001873void
Fred Drake100814d2000-07-09 15:48:49 +00001874_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001875{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001876#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001877 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001878#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001879 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001880 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001881 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001882 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001883 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001884#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001885 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1886 if (p == op)
1887 break;
1888 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001889 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001890 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001891#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892 op->_ob_next->_ob_prev = op->_ob_prev;
1893 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001894 op->_ob_next = op->_ob_prev = NULL;
Tim Peters4be93d02002-07-07 19:59:50 +00001895 _PyMAYBE_BUMP_FREECOUNT(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001896}
1897
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001898void
Fred Drake100814d2000-07-09 15:48:49 +00001899_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001900{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001901 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001902 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001903 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001904}
1905
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001906void
Fred Drake100814d2000-07-09 15:48:49 +00001907_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001908{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001909 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001910 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001911 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1912 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001913 if (PyObject_Print(op, fp, 0) != 0)
1914 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001915 putc('\n', fp);
1916 }
1917}
1918
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001919PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001920_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001921{
1922 int i, n;
1923 PyObject *t = NULL;
1924 PyObject *res, *op;
1925
1926 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1927 return NULL;
1928 op = refchain._ob_next;
1929 res = PyList_New(0);
1930 if (res == NULL)
1931 return NULL;
1932 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1933 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001934 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001935 op = op->_ob_next;
1936 if (op == &refchain)
1937 return res;
1938 }
1939 if (PyList_Append(res, op) < 0) {
1940 Py_DECREF(res);
1941 return NULL;
1942 }
1943 op = op->_ob_next;
1944 }
1945 return res;
1946}
1947
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001948#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001949
1950
1951/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001952PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001953
1954
1955/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001956int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001957
1958
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001959/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001960
Thomas Wouters334fb892000-07-25 12:56:38 +00001961void *
Fred Drake100814d2000-07-09 15:48:49 +00001962PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001963{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001964 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001965}
1966
Thomas Wouters334fb892000-07-25 12:56:38 +00001967void *
1968PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001969{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001970 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001971}
1972
1973void
Thomas Wouters334fb892000-07-25 12:56:38 +00001974PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001975{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001976 PyMem_FREE(p);
1977}
1978
1979
Guido van Rossum86610361998-04-10 22:32:46 +00001980/* These methods are used to control infinite recursion in repr, str, print,
1981 etc. Container objects that may recursively contain themselves,
1982 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1983 Py_ReprLeave() to avoid infinite recursion.
1984
1985 Py_ReprEnter() returns 0 the first time it is called for a particular
1986 object and 1 every time thereafter. It returns -1 if an exception
1987 occurred. Py_ReprLeave() has no return value.
1988
1989 See dictobject.c and listobject.c for examples of use.
1990*/
1991
1992#define KEY "Py_Repr"
1993
1994int
Fred Drake100814d2000-07-09 15:48:49 +00001995Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001996{
1997 PyObject *dict;
1998 PyObject *list;
1999 int i;
2000
2001 dict = PyThreadState_GetDict();
2002 if (dict == NULL)
2003 return -1;
2004 list = PyDict_GetItemString(dict, KEY);
2005 if (list == NULL) {
2006 list = PyList_New(0);
2007 if (list == NULL)
2008 return -1;
2009 if (PyDict_SetItemString(dict, KEY, list) < 0)
2010 return -1;
2011 Py_DECREF(list);
2012 }
2013 i = PyList_GET_SIZE(list);
2014 while (--i >= 0) {
2015 if (PyList_GET_ITEM(list, i) == obj)
2016 return 1;
2017 }
2018 PyList_Append(list, obj);
2019 return 0;
2020}
2021
2022void
Fred Drake100814d2000-07-09 15:48:49 +00002023Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002024{
2025 PyObject *dict;
2026 PyObject *list;
2027 int i;
2028
2029 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002030 if (dict == NULL)
2031 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002032 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002033 if (list == NULL || !PyList_Check(list))
2034 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002035 i = PyList_GET_SIZE(list);
2036 /* Count backwards because we always expect obj to be list[-1] */
2037 while (--i >= 0) {
2038 if (PyList_GET_ITEM(list, i) == obj) {
2039 PyList_SetSlice(list, i, i + 1, NULL);
2040 break;
2041 }
2042 }
2043}
Guido van Rossumd724b232000-03-13 16:01:29 +00002044
Tim Peters803526b2002-07-07 05:13:56 +00002045/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002046
Tim Peters803526b2002-07-07 05:13:56 +00002047/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002048int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002049
Tim Peters803526b2002-07-07 05:13:56 +00002050/* List of objects that still need to be cleaned up, singly linked via their
2051 * gc headers' gc_prev pointers.
2052 */
2053PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002054
Tim Peters803526b2002-07-07 05:13:56 +00002055/* Add op to the _PyTrash_delete_later list. Called when the current
2056 * call-stack depth gets large. op must be a currently untracked gc'ed
2057 * object, with refcount 0. Py_DECREF must already have been called on it.
2058 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002059void
Fred Drake100814d2000-07-09 15:48:49 +00002060_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002061{
Tim Peters803526b2002-07-07 05:13:56 +00002062 assert(PyObject_IS_GC(op));
2063 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2064 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002065 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002066 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002067}
2068
Tim Peters803526b2002-07-07 05:13:56 +00002069/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2070 * the call-stack unwinds again.
2071 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002072void
Fred Drake100814d2000-07-09 15:48:49 +00002073_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002074{
2075 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002076 PyObject *op = _PyTrash_delete_later;
2077 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002078
Neil Schemenauerf589c052002-03-29 03:05:54 +00002079 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002080 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002081
Tim Peters803526b2002-07-07 05:13:56 +00002082 /* Call the deallocator directly. This used to try to
2083 * fool Py_DECREF into calling it indirectly, but
2084 * Py_DECREF was already called on this object, and in
2085 * assorted non-release builds calling Py_DECREF again ends
2086 * up distorting allocation statistics.
2087 */
2088 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002089 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002090 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002091 --_PyTrash_delete_nesting;
2092 }
2093}