blob: 4cc9f6a9178558cbb55a5021871b0d8e585d237b [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;
77 type_list = tp;
78 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000079 tp->tp_allocs++;
80 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
81 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000082}
83#endif
84
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000086PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087{
Guido van Rossumb18618d2000-05-03 23:44:39 +000088 if (op == NULL) {
89 PyErr_SetString(PyExc_SystemError,
90 "NULL object passed to PyObject_Init");
91 return op;
92 }
93 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000094 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000096 return op;
97}
98
Guido van Rossumb18618d2000-05-03 23:44:39 +000099PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000100PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000101{
102 if (op == NULL) {
103 PyErr_SetString(PyExc_SystemError,
104 "NULL object passed to PyObject_InitVar");
105 return op;
106 }
107 /* Any changes should be reflected in PyObject_INIT_VAR */
108 op->ob_size = size;
109 op->ob_type = tp;
110 _Py_NewReference((PyObject *)op);
111 return op;
112}
113
114PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000115_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000116{
117 PyObject *op;
118 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
119 if (op == NULL)
120 return PyErr_NoMemory();
121 return PyObject_INIT(op, tp);
122}
123
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000124PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000125_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000127 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000128 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000129 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000131 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000132 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000133}
134
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000135/* for binary compatibility with 2.2 */
136#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000137void
Fred Drake100814d2000-07-09 15:48:49 +0000138_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000139{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000140 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141}
142
Guido van Rossum90933611991-06-07 16:10:43 +0000143int
Fred Drake100814d2000-07-09 15:48:49 +0000144PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
Guido van Rossum278ef591991-07-27 21:40:24 +0000146 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000148 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000149#ifdef USE_STACKCHECK
150 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000151 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000152 return -1;
153 }
154#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000155 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000156 if (op == NULL) {
157 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158 }
Guido van Rossum90933611991-06-07 16:10:43 +0000159 else {
160 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000161 fprintf(fp, "<refcnt %u at %p>",
162 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000163 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000164 PyObject *s;
165 if (flags & Py_PRINT_RAW)
166 s = PyObject_Str(op);
167 else
168 s = PyObject_Repr(op);
169 if (s == NULL)
170 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000171 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000172 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000173 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000174 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000175 }
Guido van Rossum90933611991-06-07 16:10:43 +0000176 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000177 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000178 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000179 if (ret == 0) {
180 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000182 clearerr(fp);
183 ret = -1;
184 }
185 }
186 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187}
188
Barry Warsaw9bf16442001-01-23 16:24:35 +0000189/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000190void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000191{
Barry Warsaweefb1072001-02-22 22:39:18 +0000192 if (op == NULL)
193 fprintf(stderr, "NULL\n");
194 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000195 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000196 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000197 fprintf(stderr, "\n"
198 "type : %s\n"
199 "refcount: %d\n"
200 "address : %p\n",
201 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
202 op->ob_refcnt,
203 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000204 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000205}
Barry Warsaw903138f2001-01-23 16:33:18 +0000206
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000208PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000210 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000211 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000212#ifdef USE_STACKCHECK
213 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000214 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000215 return NULL;
216 }
217#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000218 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000219 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000220 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000221 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000222 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000223 else {
224 PyObject *res;
225 res = (*v->ob_type->tp_repr)(v);
226 if (res == NULL)
227 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000228#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000229 if (PyUnicode_Check(res)) {
230 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000231 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000232 Py_DECREF(res);
233 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000234 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000235 else
236 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000237 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000238#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000239 if (!PyString_Check(res)) {
240 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000241 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000242 res->ob_type->tp_name);
243 Py_DECREF(res);
244 return NULL;
245 }
246 return res;
247 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248}
249
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000251PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000252{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000253 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000254
Guido van Rossumc6004111993-11-05 10:22:19 +0000255 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000256 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000257 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000258 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000259 return v;
260 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000261 if (v->ob_type->tp_str == NULL)
262 return PyObject_Repr(v);
263
264 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000265 if (res == NULL)
266 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000267#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000268 if (PyUnicode_Check(res)) {
269 PyObject* str;
270 str = PyUnicode_AsEncodedString(res, NULL, NULL);
271 Py_DECREF(res);
272 if (str)
273 res = str;
274 else
275 return NULL;
276 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000277#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000278 if (!PyString_Check(res)) {
279 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000280 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000281 res->ob_type->tp_name);
282 Py_DECREF(res);
283 return NULL;
284 }
285 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000286}
287
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000288#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000289PyObject *
290PyObject_Unicode(PyObject *v)
291{
292 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000293
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000294 if (v == NULL)
295 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000296 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000297 Py_INCREF(v);
298 return v;
299 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000300 if (PyUnicode_Check(v)) {
301 /* For a Unicode subtype that's not a Unicode object,
302 return a true Unicode object with the same data. */
303 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
304 PyUnicode_GET_SIZE(v));
305 }
306 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000307 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000308 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000309 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000310 else {
311 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000312 static PyObject *unicodestr;
313 /* XXX As soon as we have a tp_unicode slot, we should
314 check this before trying the __unicode__
315 method. */
316 if (unicodestr == NULL) {
317 unicodestr= PyString_InternFromString(
318 "__unicode__");
319 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000320 return NULL;
321 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000322 func = PyObject_GetAttr(v, unicodestr);
323 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000324 res = PyEval_CallObject(func, (PyObject *)NULL);
325 Py_DECREF(func);
326 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000327 else {
328 PyErr_Clear();
329 if (v->ob_type->tp_str != NULL)
330 res = (*v->ob_type->tp_str)(v);
331 else
332 res = PyObject_Repr(v);
333 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000334 }
335 if (res == NULL)
336 return NULL;
337 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000338 PyObject *str;
339 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000340 Py_DECREF(res);
341 if (str)
342 res = str;
343 else
344 return NULL;
345 }
346 return res;
347}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000348#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000349
350
Guido van Rossuma4073002002-05-31 20:03:54 +0000351/* Helper to warn about deprecated tp_compare return values. Return:
352 -2 for an exception;
353 -1 if v < w;
354 0 if v == w;
355 1 if v > w.
356 (This function cannot return 2.)
357*/
358static int
359adjust_tp_compare(int c)
360{
361 if (PyErr_Occurred()) {
362 if (c != -1 && c != -2) {
363 PyObject *t, *v, *tb;
364 PyErr_Fetch(&t, &v, &tb);
365 if (PyErr_Warn(PyExc_RuntimeWarning,
366 "tp_compare didn't return -1 or -2 "
367 "for exception") < 0) {
368 Py_XDECREF(t);
369 Py_XDECREF(v);
370 Py_XDECREF(tb);
371 }
372 else
373 PyErr_Restore(t, v, tb);
374 }
375 return -2;
376 }
377 else if (c < -1 || c > 1) {
378 if (PyErr_Warn(PyExc_RuntimeWarning,
379 "tp_compare didn't return -1, 0 or 1") < 0)
380 return -2;
381 else
382 return c < -1 ? -1 : 1;
383 }
384 else {
385 assert(c >= -1 && c <= 1);
386 return c;
387 }
388}
389
390
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000391/* Macro to get the tp_richcompare field of a type if defined */
392#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
393 ? (t)->tp_richcompare : NULL)
394
Guido van Rossume797ec12001-01-17 15:24:28 +0000395/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
396static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000397
Guido van Rossume797ec12001-01-17 15:24:28 +0000398/* Try a genuine rich comparison, returning an object. Return:
399 NULL for exception;
400 NotImplemented if this particular rich comparison is not implemented or
401 undefined;
402 some object not equal to NotImplemented if it is implemented
403 (this latter object may not be a Boolean).
404*/
405static PyObject *
406try_rich_compare(PyObject *v, PyObject *w, int op)
407{
408 richcmpfunc f;
409 PyObject *res;
410
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000411 if (v->ob_type != w->ob_type &&
412 PyType_IsSubtype(w->ob_type, v->ob_type) &&
413 (f = RICHCOMPARE(w->ob_type)) != NULL) {
414 res = (*f)(w, v, swapped_op[op]);
415 if (res != Py_NotImplemented)
416 return res;
417 Py_DECREF(res);
418 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000419 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000420 res = (*f)(v, w, op);
421 if (res != Py_NotImplemented)
422 return res;
423 Py_DECREF(res);
424 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000425 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000426 return (*f)(w, v, swapped_op[op]);
427 }
428 res = Py_NotImplemented;
429 Py_INCREF(res);
430 return res;
431}
432
433/* Try a genuine rich comparison, returning an int. Return:
434 -1 for exception (including the case where try_rich_compare() returns an
435 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000436 0 if the outcome is false;
437 1 if the outcome is true;
438 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000439*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000440static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000441try_rich_compare_bool(PyObject *v, PyObject *w, int op)
442{
443 PyObject *res;
444 int ok;
445
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000446 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000447 return 2; /* Shortcut, avoid INCREF+DECREF */
448 res = try_rich_compare(v, w, op);
449 if (res == NULL)
450 return -1;
451 if (res == Py_NotImplemented) {
452 Py_DECREF(res);
453 return 2;
454 }
455 ok = PyObject_IsTrue(res);
456 Py_DECREF(res);
457 return ok;
458}
459
460/* Try rich comparisons to determine a 3-way comparison. Return:
461 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000462 -1 if v < w;
463 0 if v == w;
464 1 if v > w;
465 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000466*/
467static int
468try_rich_to_3way_compare(PyObject *v, PyObject *w)
469{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000470 static struct { int op; int outcome; } tries[3] = {
471 /* Try this operator, and if it is true, use this outcome: */
472 {Py_EQ, 0},
473 {Py_LT, -1},
474 {Py_GT, 1},
475 };
476 int i;
477
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000478 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000479 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000480
481 for (i = 0; i < 3; i++) {
482 switch (try_rich_compare_bool(v, w, tries[i].op)) {
483 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000484 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000485 case 1:
486 return tries[i].outcome;
487 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000488 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000489
490 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000491}
492
493/* Try a 3-way comparison, returning an int. Return:
494 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000495 -1 if v < w;
496 0 if v == w;
497 1 if v > w;
498 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000499*/
500static int
501try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000502{
503 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000504 cmpfunc f;
505
506 /* Comparisons involving instances are given to instance_compare,
507 which has the same return conventions as this function. */
508
Guido van Rossumab3b0342001-09-18 20:38:53 +0000509 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000510 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000511 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000512 if (PyInstance_Check(w))
513 return (*w->ob_type->tp_compare)(v, w);
514
Guido van Rossumab3b0342001-09-18 20:38:53 +0000515 /* If both have the same (non-NULL) tp_compare, use it. */
516 if (f != NULL && f == w->ob_type->tp_compare) {
517 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000518 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000519 }
520
521 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
522 if (f == _PyObject_SlotCompare ||
523 w->ob_type->tp_compare == _PyObject_SlotCompare)
524 return _PyObject_SlotCompare(v, w);
525
Guido van Rossume797ec12001-01-17 15:24:28 +0000526 /* Try coercion; if it fails, give up */
527 c = PyNumber_CoerceEx(&v, &w);
528 if (c < 0)
529 return -2;
530 if (c > 0)
531 return 2;
532
533 /* Try v's comparison, if defined */
534 if ((f = v->ob_type->tp_compare) != NULL) {
535 c = (*f)(v, w);
536 Py_DECREF(v);
537 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000538 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000539 }
540
541 /* Try w's comparison, if defined */
542 if ((f = w->ob_type->tp_compare) != NULL) {
543 c = (*f)(w, v); /* swapped! */
544 Py_DECREF(v);
545 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000546 c = adjust_tp_compare(c);
547 if (c >= -1)
548 return -c; /* Swapped! */
549 else
550 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000551 }
552
553 /* No comparison defined */
554 Py_DECREF(v);
555 Py_DECREF(w);
556 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000557}
558
Guido van Rossume797ec12001-01-17 15:24:28 +0000559/* Final fallback 3-way comparison, returning an int. Return:
560 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000561 -1 if v < w;
562 0 if v == w;
563 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000564*/
565static int
566default_3way_compare(PyObject *v, PyObject *w)
567{
568 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000569 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000570
571 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000572 /* When comparing these pointers, they must be cast to
573 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
574 * uintptr_t). ANSI specifies that pointer compares other
575 * than == and != to non-related structures are undefined.
576 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000577 Py_uintptr_t vv = (Py_uintptr_t)v;
578 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000579 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
580 }
581
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000582#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000583 /* Special case for Unicode */
584 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
585 c = PyUnicode_Compare(v, w);
586 if (!PyErr_Occurred())
587 return c;
588 /* TypeErrors are ignored: if Unicode coercion fails due
589 to one of the arguments not having the right type, we
590 continue as defined by the coercion protocol (see
591 above). Luckily, decoding errors are reported as
592 ValueErrors and are not masked by this technique. */
593 if (!PyErr_ExceptionMatches(PyExc_TypeError))
594 return -2;
595 PyErr_Clear();
596 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000597#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000598
Guido van Rossum0871e932001-01-22 19:28:09 +0000599 /* None is smaller than anything */
600 if (v == Py_None)
601 return -1;
602 if (w == Py_None)
603 return 1;
604
Guido van Rossume797ec12001-01-17 15:24:28 +0000605 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000606 if (v->ob_type->tp_as_number)
607 vname = "";
608 else
609 vname = v->ob_type->tp_name;
610 if (w->ob_type->tp_as_number)
611 wname = "";
612 else
613 wname = w->ob_type->tp_name;
614 c = strcmp(vname, wname);
615 if (c < 0)
616 return -1;
617 if (c > 0)
618 return 1;
619 /* Same type name, or (more likely) incomparable numeric types */
620 return ((Py_uintptr_t)(v->ob_type) < (
621 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000622}
623
624#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
625
Tim Peters6d60b2e2001-05-07 20:53:51 +0000626/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000627 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000628 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000629 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000630 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000631 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000632 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000633*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000634static int
Fred Drake100814d2000-07-09 15:48:49 +0000635do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000636{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000637 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000638 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000639
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000640 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000641 && (f = v->ob_type->tp_compare) != NULL) {
642 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000643 if (PyInstance_Check(v)) {
644 /* Instance tp_compare has a different signature.
645 But if it returns undefined we fall through. */
646 if (c != 2)
647 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000648 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000649 }
650 else
651 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000652 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000653 /* We only get here if one of the following is true:
654 a) v and w have different types
655 b) v and w have the same type, which doesn't have tp_compare
656 c) v and w are instances, and either __cmp__ is not defined or
657 __cmp__ returns NotImplemented
658 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000659 c = try_rich_to_3way_compare(v, w);
660 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000661 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000662 c = try_3way_compare(v, w);
663 if (c < 2)
664 return c;
665 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000666}
667
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000668/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000669 some types) and decremented on exit. If the count exceeds the
670 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000671
672 This is a tunable parameter that should only affect the performance
673 of comparisons, nothing else. Setting it high makes comparing deeply
674 nested non-cyclical data structures faster, but makes comparing cyclical
675 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000676*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000677#define NESTING_LIMIT 20
678
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000679static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000680
681static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000682get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000683{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000684 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000685 PyObject *tstate_dict, *inprogress;
686
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000687 if (key == NULL) {
688 key = PyString_InternFromString("cmp_state");
689 if (key == NULL)
690 return NULL;
691 }
692
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000693 tstate_dict = PyThreadState_GetDict();
694 if (tstate_dict == NULL) {
695 PyErr_BadInternalCall();
696 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000697 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000698
Tim Peters803526b2002-07-07 05:13:56 +0000699 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000700 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000701 inprogress = PyDict_New();
702 if (inprogress == NULL)
703 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000704 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000705 Py_DECREF(inprogress);
706 return NULL;
707 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000708 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000709 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000710
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000711 return inprogress;
712}
713
714static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000715check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000716{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000717 PyObject *inprogress;
718 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000719 Py_uintptr_t iv = (Py_uintptr_t)v;
720 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000721 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000722
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000723 inprogress = get_inprogress_dict();
724 if (inprogress == NULL)
725 return NULL;
726
727 token = PyTuple_New(3);
728 if (token == NULL)
729 return NULL;
730
731 if (iv <= iw) {
732 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
733 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
734 if (op >= 0)
735 op = swapped_op[op];
736 } else {
737 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
738 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
739 }
740 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
741 if (x == NULL || y == NULL || z == NULL) {
742 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000743 return NULL;
744 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000745
746 if (PyDict_GetItem(inprogress, token) != NULL) {
747 Py_DECREF(token);
748 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000749 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000750
751 if (PyDict_SetItem(inprogress, token, token) < 0) {
752 Py_DECREF(token);
753 return NULL;
754 }
755
756 return token;
757}
758
759static void
760delete_token(PyObject *token)
761{
762 PyObject *inprogress;
763
764 if (token == NULL || token == Py_None)
765 return;
766 inprogress = get_inprogress_dict();
767 if (inprogress == NULL)
768 PyErr_Clear();
769 else
770 PyDict_DelItem(inprogress, token);
771 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000772}
773
Tim Petersc99213f2001-11-04 05:57:16 +0000774/* Compare v to w. Return
775 -1 if v < w or exception (PyErr_Occurred() true in latter case).
776 0 if v == w.
777 1 if v > w.
778 XXX The docs (C API manual) say the return value is undefined in case
779 XXX of error.
780*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000781int
Fred Drake100814d2000-07-09 15:48:49 +0000782PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000784 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000785 int result;
786
Jack Jansend49cbe12000-08-22 21:52:51 +0000787#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000788 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000789 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000790 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000791 }
792#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000793 if (v == NULL || w == NULL) {
794 PyErr_BadInternalCall();
795 return -1;
796 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000797 if (v == w)
798 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000799 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000800 compare_nesting++;
801 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000802 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000803 || (vtp->tp_as_sequence
804 && !PyString_Check(v)
805 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000806 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000807 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000808
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000809 if (token == NULL) {
810 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000811 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000812 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000813 /* already comparing these objects. assume
814 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000815 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000816 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000817 else {
818 result = do_cmp(v, w);
819 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000820 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000821 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000822 else {
823 result = do_cmp(v, w);
824 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000825 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000826 return result < 0 ? -1 : result;
827}
828
Tim Petersc99213f2001-11-04 05:57:16 +0000829/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000830static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000831convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000832{
Guido van Rossume797ec12001-01-17 15:24:28 +0000833 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000834 switch (op) {
835 case Py_LT: c = c < 0; break;
836 case Py_LE: c = c <= 0; break;
837 case Py_EQ: c = c == 0; break;
838 case Py_NE: c = c != 0; break;
839 case Py_GT: c = c > 0; break;
840 case Py_GE: c = c >= 0; break;
841 }
842 result = c ? Py_True : Py_False;
843 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000844 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000845}
Tim Peters803526b2002-07-07 05:13:56 +0000846
Tim Petersc99213f2001-11-04 05:57:16 +0000847/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
848 Return
849 NULL if error
850 Py_True if v op w
851 Py_False if not (v op w)
852*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000853static PyObject *
854try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
855{
856 int c;
857
858 c = try_3way_compare(v, w);
859 if (c >= 2)
860 c = default_3way_compare(v, w);
861 if (c <= -2)
862 return NULL;
863 return convert_3way_to_object(op, c);
864}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000865
Tim Petersc99213f2001-11-04 05:57:16 +0000866/* Do rich comparison on v and w. Return
867 NULL if error
868 Else a new reference to an object other than Py_NotImplemented, usually(?):
869 Py_True if v op w
870 Py_False if not (v op w)
871*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000872static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000873do_richcmp(PyObject *v, PyObject *w, int op)
874{
875 PyObject *res;
876
877 res = try_rich_compare(v, w, op);
878 if (res != Py_NotImplemented)
879 return res;
880 Py_DECREF(res);
881
882 return try_3way_to_rich_compare(v, w, op);
883}
884
Tim Petersc99213f2001-11-04 05:57:16 +0000885/* Return:
886 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000887 some object not equal to NotImplemented if it is implemented
888 (this latter object may not be a Boolean).
889*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000890PyObject *
891PyObject_RichCompare(PyObject *v, PyObject *w, int op)
892{
893 PyObject *res;
894
895 assert(Py_LT <= op && op <= Py_GE);
896
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000897 compare_nesting++;
898 if (compare_nesting > NESTING_LIMIT &&
899 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000900 || (v->ob_type->tp_as_sequence
901 && !PyString_Check(v)
902 && !PyTuple_Check(v)))) {
Tim Peters67754e92001-11-04 07:29:31 +0000903
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000904 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000905 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000906 if (token == NULL) {
907 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000908 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000909 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000910 else if (token == Py_None) {
911 /* already comparing these objects with this operator.
912 assume they're equal until shown otherwise */
913 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000914 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000915 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000916 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000917 else {
918 PyErr_SetString(PyExc_ValueError,
919 "can't order recursive values");
920 res = NULL;
921 }
922 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000923 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000924 else {
925 res = do_richcmp(v, w, op);
926 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000927 }
Tim Peters67754e92001-11-04 07:29:31 +0000928 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000929 }
Tim Peters67754e92001-11-04 07:29:31 +0000930
931 /* No nesting extremism.
932 If the types are equal, and not old-style instances, try to
933 get out cheap (don't bother with coercions etc.). */
934 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
935 cmpfunc fcmp;
936 richcmpfunc frich = RICHCOMPARE(v->ob_type);
937 /* If the type has richcmp, try it first. try_rich_compare
938 tries it two-sided, which is not needed since we've a
939 single type only. */
940 if (frich != NULL) {
941 res = (*frich)(v, w, op);
942 if (res != Py_NotImplemented)
943 goto Done;
944 Py_DECREF(res);
945 }
946 /* No richcmp, or this particular richmp not implemented.
947 Try 3-way cmp. */
948 fcmp = v->ob_type->tp_compare;
949 if (fcmp != NULL) {
950 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000951 c = adjust_tp_compare(c);
952 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000953 res = NULL;
954 goto Done;
955 }
956 res = convert_3way_to_object(op, c);
957 goto Done;
958 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000959 }
Tim Peters67754e92001-11-04 07:29:31 +0000960
961 /* Fast path not taken, or couldn't deliver a useful result. */
962 res = do_richcmp(v, w, op);
963Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000964 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000965 return res;
966}
967
Tim Petersde9725f2001-05-05 10:06:17 +0000968/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000969int
970PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
971{
972 PyObject *res = PyObject_RichCompare(v, w, op);
973 int ok;
974
975 if (res == NULL)
976 return -1;
977 ok = PyObject_IsTrue(res);
978 Py_DECREF(res);
979 return ok;
980}
Fred Drake13634cf2000-06-29 19:17:04 +0000981
982/* Set of hash utility functions to help maintaining the invariant that
983 iff a==b then hash(a)==hash(b)
984
985 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
986*/
987
988long
Fred Drake100814d2000-07-09 15:48:49 +0000989_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000990{
Tim Peters39dce292000-08-15 03:34:48 +0000991 double intpart, fractpart;
992 int expo;
993 long hipart;
994 long x; /* the final hash value */
995 /* This is designed so that Python numbers of different types
996 * that compare equal hash to the same value; otherwise comparisons
997 * of mapping keys will turn out weird.
998 */
999
1000#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1001{
1002 extended e;
1003 fractpart = modf(v, &e);
1004 intpart = e;
1005}
1006#else
1007 fractpart = modf(v, &intpart);
1008#endif
1009 if (fractpart == 0.0) {
1010 /* This must return the same hash as an equal int or long. */
1011 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1012 /* Convert to long and use its hash. */
1013 PyObject *plong; /* converted to Python long */
1014 if (Py_IS_INFINITY(intpart))
1015 /* can't convert to long int -- arbitrary */
1016 v = v < 0 ? -271828.0 : 314159.0;
1017 plong = PyLong_FromDouble(v);
1018 if (plong == NULL)
1019 return -1;
1020 x = PyObject_Hash(plong);
1021 Py_DECREF(plong);
1022 return x;
1023 }
1024 /* Fits in a C long == a Python int, so is its own hash. */
1025 x = (long)intpart;
1026 if (x == -1)
1027 x = -2;
1028 return x;
1029 }
1030 /* The fractional part is non-zero, so we don't have to worry about
1031 * making this match the hash of some other type.
1032 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001033 * Since the VAX D double format has 56 mantissa bits, which is the
1034 * most of any double format in use, each of these parts may have as
1035 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001036 * So, assuming sizeof(long) >= 4, each part can be broken into two
1037 * longs; frexp and multiplication are used to do that.
1038 * Also, since the Cray double format has 15 exponent bits, which is
1039 * the most of any double format in use, shifting the exponent field
1040 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001041 */
Tim Peters39dce292000-08-15 03:34:48 +00001042 v = frexp(v, &expo);
1043 v *= 2147483648.0; /* 2**31 */
1044 hipart = (long)v; /* take the top 32 bits */
1045 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1046 x = hipart + (long)v + (expo << 15);
1047 if (x == -1)
1048 x = -2;
1049 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001050}
1051
1052long
Fred Drake100814d2000-07-09 15:48:49 +00001053_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001054{
1055#if SIZEOF_LONG >= SIZEOF_VOID_P
1056 return (long)p;
1057#else
1058 /* convert to a Python long and hash that */
1059 PyObject* longobj;
1060 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001061
Fred Drake13634cf2000-06-29 19:17:04 +00001062 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1063 x = -1;
1064 goto finally;
1065 }
1066 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001067
Fred Drake13634cf2000-06-29 19:17:04 +00001068finally:
1069 Py_XDECREF(longobj);
1070 return x;
1071#endif
1072}
1073
1074
Guido van Rossum9bfef441993-03-29 10:43:31 +00001075long
Fred Drake100814d2000-07-09 15:48:49 +00001076PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001077{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001078 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001079 if (tp->tp_hash != NULL)
1080 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001081 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001082 return _Py_HashPointer(v); /* Use address as hash value */
1083 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001084 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001086 return -1;
1087}
1088
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001089PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001090PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001091{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001093
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001095 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096 w = PyString_InternFromString(name);
1097 if (w == NULL)
1098 return NULL;
1099 res = PyObject_GetAttr(v, w);
1100 Py_XDECREF(w);
1101 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001102}
1103
1104int
Fred Drake100814d2000-07-09 15:48:49 +00001105PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001106{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001107 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001108 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001109 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001110 return 1;
1111 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001112 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001113 return 0;
1114}
1115
1116int
Fred Drake100814d2000-07-09 15:48:49 +00001117PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001118{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 PyObject *s;
1120 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001121
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001123 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001124 s = PyString_InternFromString(name);
1125 if (s == NULL)
1126 return -1;
1127 res = PyObject_SetAttr(v, s, w);
1128 Py_XDECREF(s);
1129 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001130}
1131
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001132PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001133PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001134{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 PyTypeObject *tp = v->ob_type;
1136
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001137 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001138#ifdef Py_USING_UNICODE
1139 /* The Unicode to string conversion is done here because the
1140 existing tp_getattro slots expect a string object as name
1141 and we wouldn't want to break those. */
1142 if (PyUnicode_Check(name)) {
1143 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1144 if (name == NULL)
1145 return NULL;
1146 }
1147 else
1148#endif
1149 {
1150 PyErr_SetString(PyExc_TypeError,
1151 "attribute name must be string");
1152 return NULL;
1153 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001154 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 if (tp->tp_getattro != NULL)
1156 return (*tp->tp_getattro)(v, name);
1157 if (tp->tp_getattr != NULL)
1158 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1159 PyErr_Format(PyExc_AttributeError,
1160 "'%.50s' object has no attribute '%.400s'",
1161 tp->tp_name, PyString_AS_STRING(name));
1162 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001163}
1164
1165int
Fred Drake100814d2000-07-09 15:48:49 +00001166PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001167{
1168 PyObject *res = PyObject_GetAttr(v, name);
1169 if (res != NULL) {
1170 Py_DECREF(res);
1171 return 1;
1172 }
1173 PyErr_Clear();
1174 return 0;
1175}
1176
1177int
Fred Drake100814d2000-07-09 15:48:49 +00001178PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001179{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001181 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001182
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001183 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001184#ifdef Py_USING_UNICODE
1185 /* The Unicode to string conversion is done here because the
1186 existing tp_setattro slots expect a string object as name
1187 and we wouldn't want to break those. */
1188 if (PyUnicode_Check(name)) {
1189 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1190 if (name == NULL)
1191 return -1;
1192 }
Tim Peters803526b2002-07-07 05:13:56 +00001193 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001194#endif
1195 {
1196 PyErr_SetString(PyExc_TypeError,
1197 "attribute name must be string");
1198 return -1;
1199 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001200 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001201 else
1202 Py_INCREF(name);
1203
1204 PyString_InternInPlace(&name);
1205 if (tp->tp_setattro != NULL) {
1206 err = (*tp->tp_setattro)(v, name, value);
1207 Py_DECREF(name);
1208 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001209 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001210 if (tp->tp_setattr != NULL) {
1211 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1212 Py_DECREF(name);
1213 return err;
1214 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001215 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1217 PyErr_Format(PyExc_TypeError,
1218 "'%.100s' object has no attributes "
1219 "(%s .%.100s)",
1220 tp->tp_name,
1221 value==NULL ? "del" : "assign to",
1222 PyString_AS_STRING(name));
1223 else
1224 PyErr_Format(PyExc_TypeError,
1225 "'%.100s' object has only read-only attributes "
1226 "(%s .%.100s)",
1227 tp->tp_name,
1228 value==NULL ? "del" : "assign to",
1229 PyString_AS_STRING(name));
1230 return -1;
1231}
1232
1233/* Helper to get a pointer to an object's __dict__ slot, if any */
1234
1235PyObject **
1236_PyObject_GetDictPtr(PyObject *obj)
1237{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001238 long dictoffset;
1239 PyTypeObject *tp = obj->ob_type;
1240
1241 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1242 return NULL;
1243 dictoffset = tp->tp_dictoffset;
1244 if (dictoffset == 0)
1245 return NULL;
1246 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001247 int tsize;
1248 size_t size;
1249
1250 tsize = ((PyVarObject *)obj)->ob_size;
1251 if (tsize < 0)
1252 tsize = -tsize;
1253 size = _PyObject_VAR_SIZE(tp, tsize);
1254
Tim Peters6d483d32001-10-06 21:27:34 +00001255 dictoffset += (long)size;
1256 assert(dictoffset > 0);
1257 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258 }
1259 return (PyObject **) ((char *)obj + dictoffset);
1260}
1261
1262/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1263
1264PyObject *
1265PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1266{
1267 PyTypeObject *tp = obj->ob_type;
1268 PyObject *descr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001269 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 descrgetfunc f;
1271 PyObject **dictptr;
1272
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001273 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001274#ifdef Py_USING_UNICODE
1275 /* The Unicode to string conversion is done here because the
1276 existing tp_setattro slots expect a string object as name
1277 and we wouldn't want to break those. */
1278 if (PyUnicode_Check(name)) {
1279 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1280 if (name == NULL)
1281 return NULL;
1282 }
Tim Peters803526b2002-07-07 05:13:56 +00001283 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001284#endif
1285 {
1286 PyErr_SetString(PyExc_TypeError,
1287 "attribute name must be string");
1288 return NULL;
1289 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001290 }
1291 else
1292 Py_INCREF(name);
1293
Tim Peters6d6c1a32001-08-02 04:15:00 +00001294 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001295 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001296 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 }
1298
1299 descr = _PyType_Lookup(tp, name);
1300 f = NULL;
1301 if (descr != NULL) {
1302 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001303 if (f != NULL && PyDescr_IsData(descr)) {
1304 res = f(descr, obj, (PyObject *)obj->ob_type);
1305 goto done;
1306 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307 }
1308
1309 dictptr = _PyObject_GetDictPtr(obj);
1310 if (dictptr != NULL) {
1311 PyObject *dict = *dictptr;
1312 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001313 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314 if (res != NULL) {
1315 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001316 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317 }
1318 }
1319 }
1320
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001321 if (f != NULL) {
1322 res = f(descr, obj, (PyObject *)obj->ob_type);
1323 goto done;
1324 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325
1326 if (descr != NULL) {
1327 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001328 res = descr;
1329 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330 }
1331
1332 PyErr_Format(PyExc_AttributeError,
1333 "'%.50s' object has no attribute '%.400s'",
1334 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001335 done:
1336 Py_DECREF(name);
1337 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338}
1339
1340int
1341PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1342{
1343 PyTypeObject *tp = obj->ob_type;
1344 PyObject *descr;
1345 descrsetfunc f;
1346 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001347 int res = -1;
1348
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001349 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001350#ifdef Py_USING_UNICODE
1351 /* The Unicode to string conversion is done here because the
1352 existing tp_setattro slots expect a string object as name
1353 and we wouldn't want to break those. */
1354 if (PyUnicode_Check(name)) {
1355 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1356 if (name == NULL)
1357 return -1;
1358 }
Tim Peters803526b2002-07-07 05:13:56 +00001359 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001360#endif
1361 {
1362 PyErr_SetString(PyExc_TypeError,
1363 "attribute name must be string");
1364 return -1;
1365 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001366 }
1367 else
1368 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369
1370 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001371 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001372 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001373 }
1374
1375 descr = _PyType_Lookup(tp, name);
1376 f = NULL;
1377 if (descr != NULL) {
1378 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001379 if (f != NULL && PyDescr_IsData(descr)) {
1380 res = f(descr, obj, value);
1381 goto done;
1382 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001383 }
1384
1385 dictptr = _PyObject_GetDictPtr(obj);
1386 if (dictptr != NULL) {
1387 PyObject *dict = *dictptr;
1388 if (dict == NULL && value != NULL) {
1389 dict = PyDict_New();
1390 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001391 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392 *dictptr = dict;
1393 }
1394 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395 if (value == NULL)
1396 res = PyDict_DelItem(dict, name);
1397 else
1398 res = PyDict_SetItem(dict, name, value);
1399 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1400 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001401 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402 }
1403 }
1404
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001405 if (f != NULL) {
1406 res = f(descr, obj, value);
1407 goto done;
1408 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001409
1410 if (descr == NULL) {
1411 PyErr_Format(PyExc_AttributeError,
1412 "'%.50s' object has no attribute '%.400s'",
1413 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001414 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415 }
1416
1417 PyErr_Format(PyExc_AttributeError,
1418 "'%.50s' object attribute '%.400s' is read-only",
1419 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001420 done:
1421 Py_DECREF(name);
1422 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001423}
1424
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001425/* Test a value used as condition, e.g., in a for or if statement.
1426 Return -1 if an error occurred */
1427
1428int
Fred Drake100814d2000-07-09 15:48:49 +00001429PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001430{
1431 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001432 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001433 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001434 else if (v->ob_type->tp_as_number != NULL &&
1435 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001436 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001437 else if (v->ob_type->tp_as_mapping != NULL &&
1438 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001439 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001440 else if (v->ob_type->tp_as_sequence != NULL &&
1441 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001442 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1443 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001444 return 1;
1445 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001446}
1447
Tim Peters803526b2002-07-07 05:13:56 +00001448/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001449 Return -1 if an error occurred */
1450
1451int
Fred Drake100814d2000-07-09 15:48:49 +00001452PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001453{
1454 int res;
1455 res = PyObject_IsTrue(v);
1456 if (res < 0)
1457 return res;
1458 return res == 0;
1459}
1460
Guido van Rossum5524a591995-01-10 15:26:20 +00001461/* Coerce two numeric types to the "larger" one.
1462 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001463 Return value:
1464 -1 if an error occurred;
1465 0 if the coercion succeeded (and then the reference counts are increased);
1466 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001467*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001468int
Fred Drake100814d2000-07-09 15:48:49 +00001469PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001470{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001471 register PyObject *v = *pv;
1472 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001473 int res;
1474
Guido van Rossum517c7d42002-04-26 02:49:14 +00001475 /* Shortcut only for old-style types */
1476 if (v->ob_type == w->ob_type &&
1477 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1478 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001479 Py_INCREF(v);
1480 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001481 return 0;
1482 }
1483 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1484 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1485 if (res <= 0)
1486 return res;
1487 }
1488 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1489 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1490 if (res <= 0)
1491 return res;
1492 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001493 return 1;
1494}
1495
Guido van Rossume797ec12001-01-17 15:24:28 +00001496/* Coerce two numeric types to the "larger" one.
1497 Increment the reference count on each argument.
1498 Return -1 and raise an exception if no coercion is possible
1499 (and then no reference count is incremented).
1500*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001501int
Fred Drake100814d2000-07-09 15:48:49 +00001502PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001503{
1504 int err = PyNumber_CoerceEx(pv, pw);
1505 if (err <= 0)
1506 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001507 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001508 return -1;
1509}
1510
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001511
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001512/* Test whether an object can be called */
1513
1514int
Fred Drake100814d2000-07-09 15:48:49 +00001515PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001516{
1517 if (x == NULL)
1518 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001519 if (PyInstance_Check(x)) {
1520 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001521 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001522 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001523 return 0;
1524 }
1525 /* Could test recursively but don't, for fear of endless
1526 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001527 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001528 return 1;
1529 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001530 else {
1531 return x->ob_type->tp_call != NULL;
1532 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001533}
1534
Tim Peters7eea37e2001-09-04 22:08:56 +00001535/* Helper for PyObject_Dir.
1536 Merge the __dict__ of aclass into dict, and recursively also all
1537 the __dict__s of aclass's base classes. The order of merging isn't
1538 defined, as it's expected that only the final set of dict keys is
1539 interesting.
1540 Return 0 on success, -1 on error.
1541*/
1542
1543static int
1544merge_class_dict(PyObject* dict, PyObject* aclass)
1545{
1546 PyObject *classdict;
1547 PyObject *bases;
1548
1549 assert(PyDict_Check(dict));
1550 assert(aclass);
1551
1552 /* Merge in the type's dict (if any). */
1553 classdict = PyObject_GetAttrString(aclass, "__dict__");
1554 if (classdict == NULL)
1555 PyErr_Clear();
1556 else {
1557 int status = PyDict_Update(dict, classdict);
1558 Py_DECREF(classdict);
1559 if (status < 0)
1560 return -1;
1561 }
1562
1563 /* Recursively merge in the base types' (if any) dicts. */
1564 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001565 if (bases == NULL)
1566 PyErr_Clear();
1567 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001568 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001569 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001570 n = PySequence_Size(bases); /* This better be right */
1571 if (n < 0)
1572 PyErr_Clear();
1573 else {
1574 for (i = 0; i < n; i++) {
1575 PyObject *base = PySequence_GetItem(bases, i);
1576 if (base == NULL) {
1577 Py_DECREF(bases);
1578 return -1;
1579 }
1580 if (merge_class_dict(dict, base) < 0) {
1581 Py_DECREF(bases);
1582 return -1;
1583 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001584 }
1585 }
1586 Py_DECREF(bases);
1587 }
1588 return 0;
1589}
1590
Tim Peters305b5852001-09-17 02:38:46 +00001591/* Helper for PyObject_Dir.
1592 If obj has an attr named attrname that's a list, merge its string
1593 elements into keys of dict.
1594 Return 0 on success, -1 on error. Errors due to not finding the attr,
1595 or the attr not being a list, are suppressed.
1596*/
1597
1598static int
1599merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1600{
1601 PyObject *list;
1602 int result = 0;
1603
1604 assert(PyDict_Check(dict));
1605 assert(obj);
1606 assert(attrname);
1607
1608 list = PyObject_GetAttrString(obj, attrname);
1609 if (list == NULL)
1610 PyErr_Clear();
1611
1612 else if (PyList_Check(list)) {
1613 int i;
1614 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1615 PyObject *item = PyList_GET_ITEM(list, i);
1616 if (PyString_Check(item)) {
1617 result = PyDict_SetItem(dict, item, Py_None);
1618 if (result < 0)
1619 break;
1620 }
1621 }
1622 }
1623
1624 Py_XDECREF(list);
1625 return result;
1626}
1627
Tim Peters7eea37e2001-09-04 22:08:56 +00001628/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1629 docstring, which should be kept in synch with this implementation. */
1630
1631PyObject *
1632PyObject_Dir(PyObject *arg)
1633{
1634 /* Set exactly one of these non-NULL before the end. */
1635 PyObject *result = NULL; /* result list */
1636 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1637
1638 /* If NULL arg, return the locals. */
1639 if (arg == NULL) {
1640 PyObject *locals = PyEval_GetLocals();
1641 if (locals == NULL)
1642 goto error;
1643 result = PyDict_Keys(locals);
1644 if (result == NULL)
1645 goto error;
1646 }
1647
1648 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001649 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001650 masterdict = PyObject_GetAttrString(arg, "__dict__");
1651 if (masterdict == NULL)
1652 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001653 if (!PyDict_Check(masterdict)) {
1654 PyErr_SetString(PyExc_TypeError,
1655 "module.__dict__ is not a dictionary");
1656 goto error;
1657 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001658 }
1659
1660 /* Elif some form of type or class, grab its dict and its bases.
1661 We deliberately don't suck up its __class__, as methods belonging
1662 to the metaclass would probably be more confusing than helpful. */
1663 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1664 masterdict = PyDict_New();
1665 if (masterdict == NULL)
1666 goto error;
1667 if (merge_class_dict(masterdict, arg) < 0)
1668 goto error;
1669 }
1670
1671 /* Else look at its dict, and the attrs reachable from its class. */
1672 else {
1673 PyObject *itsclass;
1674 /* Create a dict to start with. CAUTION: Not everything
1675 responding to __dict__ returns a dict! */
1676 masterdict = PyObject_GetAttrString(arg, "__dict__");
1677 if (masterdict == NULL) {
1678 PyErr_Clear();
1679 masterdict = PyDict_New();
1680 }
1681 else if (!PyDict_Check(masterdict)) {
1682 Py_DECREF(masterdict);
1683 masterdict = PyDict_New();
1684 }
1685 else {
1686 /* The object may have returned a reference to its
1687 dict, so copy it to avoid mutating it. */
1688 PyObject *temp = PyDict_Copy(masterdict);
1689 Py_DECREF(masterdict);
1690 masterdict = temp;
1691 }
1692 if (masterdict == NULL)
1693 goto error;
1694
Tim Peters305b5852001-09-17 02:38:46 +00001695 /* Merge in __members__ and __methods__ (if any).
1696 XXX Would like this to go away someday; for now, it's
1697 XXX needed to get at im_self etc of method objects. */
1698 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1699 goto error;
1700 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1701 goto error;
1702
Tim Peters7eea37e2001-09-04 22:08:56 +00001703 /* Merge in attrs reachable from its class.
1704 CAUTION: Not all objects have a __class__ attr. */
1705 itsclass = PyObject_GetAttrString(arg, "__class__");
1706 if (itsclass == NULL)
1707 PyErr_Clear();
1708 else {
1709 int status = merge_class_dict(masterdict, itsclass);
1710 Py_DECREF(itsclass);
1711 if (status < 0)
1712 goto error;
1713 }
1714 }
1715
1716 assert((result == NULL) ^ (masterdict == NULL));
1717 if (masterdict != NULL) {
1718 /* The result comes from its keys. */
1719 assert(result == NULL);
1720 result = PyDict_Keys(masterdict);
1721 if (result == NULL)
1722 goto error;
1723 }
1724
1725 assert(result);
1726 if (PyList_Sort(result) != 0)
1727 goto error;
1728 else
1729 goto normal_return;
1730
1731 error:
1732 Py_XDECREF(result);
1733 result = NULL;
1734 /* fall through */
1735 normal_return:
1736 Py_XDECREF(masterdict);
1737 return result;
1738}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001739
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001740/*
1741NoObject is usable as a non-NULL undefined value, used by the macro None.
1742There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001743so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001744(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001745*/
1746
Guido van Rossum0c182a11992-03-27 17:26:13 +00001747/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001748static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001749none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001750{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001751 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001752}
1753
Barry Warsaw9bf16442001-01-23 16:24:35 +00001754/* ARGUSED */
1755static void
Tim Peters803526b2002-07-07 05:13:56 +00001756none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001757{
1758 /* This should never get called, but we also don't want to SEGV if
1759 * we accidently decref None out of existance.
1760 */
1761 abort();
1762}
1763
1764
Guido van Rossumba21a492001-08-16 08:17:26 +00001765static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001766 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001767 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001768 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001769 0,
1770 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001771 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001772 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001773 0, /*tp_getattr*/
1774 0, /*tp_setattr*/
1775 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001776 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001777 0, /*tp_as_number*/
1778 0, /*tp_as_sequence*/
1779 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001780 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001781};
1782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001783PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001784 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001785};
1786
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001787/* NotImplemented is an object that can be used to signal that an
1788 operation is not implemented for the given type combination. */
1789
1790static PyObject *
1791NotImplemented_repr(PyObject *op)
1792{
1793 return PyString_FromString("NotImplemented");
1794}
1795
1796static PyTypeObject PyNotImplemented_Type = {
1797 PyObject_HEAD_INIT(&PyType_Type)
1798 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001799 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001800 0,
1801 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001802 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001803 0, /*tp_print*/
1804 0, /*tp_getattr*/
1805 0, /*tp_setattr*/
1806 0, /*tp_compare*/
1807 (reprfunc)NotImplemented_repr, /*tp_repr*/
1808 0, /*tp_as_number*/
1809 0, /*tp_as_sequence*/
1810 0, /*tp_as_mapping*/
1811 0, /*tp_hash */
1812};
1813
1814PyObject _Py_NotImplementedStruct = {
1815 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1816};
1817
Guido van Rossumba21a492001-08-16 08:17:26 +00001818void
1819_Py_ReadyTypes(void)
1820{
1821 if (PyType_Ready(&PyType_Type) < 0)
1822 Py_FatalError("Can't initialize 'type'");
1823
Guido van Rossum77f6a652002-04-03 22:41:51 +00001824 if (PyType_Ready(&PyBool_Type) < 0)
1825 Py_FatalError("Can't initialize 'bool'");
1826
Guido van Rossumcacfc072002-05-24 19:01:59 +00001827 if (PyType_Ready(&PyString_Type) < 0)
1828 Py_FatalError("Can't initialize 'str'");
1829
Guido van Rossumba21a492001-08-16 08:17:26 +00001830 if (PyType_Ready(&PyList_Type) < 0)
1831 Py_FatalError("Can't initialize 'list'");
1832
1833 if (PyType_Ready(&PyNone_Type) < 0)
1834 Py_FatalError("Can't initialize type(None)");
1835
1836 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1837 Py_FatalError("Can't initialize type(NotImplemented)");
1838}
1839
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001840
Guido van Rossum84a90321996-05-22 16:34:47 +00001841#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001843static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001845void
Fred Drake100814d2000-07-09 15:48:49 +00001846_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001847{
1848 refchain._ob_prev = refchain._ob_next = &refchain;
1849 _Py_RefTotal = 0;
1850}
1851
1852void
Fred Drake100814d2000-07-09 15:48:49 +00001853_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001855 _Py_RefTotal++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001856 op->ob_refcnt = 1;
1857 op->_ob_next = refchain._ob_next;
1858 op->_ob_prev = &refchain;
1859 refchain._ob_next->_ob_prev = op;
1860 refchain._ob_next = op;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +00001861#ifdef COUNT_ALLOCS
1862 inc_count(op->ob_type);
1863#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001864}
1865
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001866void
Fred Drake100814d2000-07-09 15:48:49 +00001867_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001868{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001869#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001870 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001871#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001872 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001873 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001874 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001875 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001877#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001878 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1879 if (p == op)
1880 break;
1881 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001882 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001883 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001884#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001885 op->_ob_next->_ob_prev = op->_ob_prev;
1886 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001887 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001888#ifdef COUNT_ALLOCS
Tim Peters6d6c1a32001-08-02 04:15:00 +00001889 op->ob_type->tp_frees++;
Guido van Rossumd8953cb1995-04-06 14:46:26 +00001890#endif
Guido van Rossum3f5da241990-12-20 15:06:42 +00001891}
1892
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001893void
Fred Drake100814d2000-07-09 15:48:49 +00001894_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001895{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001896 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001897 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001898 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001899}
1900
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001901void
Fred Drake100814d2000-07-09 15:48:49 +00001902_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001903{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001904 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001905 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001906 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1907 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001908 if (PyObject_Print(op, fp, 0) != 0)
1909 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001910 putc('\n', fp);
1911 }
1912}
1913
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001914PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001915_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001916{
1917 int i, n;
1918 PyObject *t = NULL;
1919 PyObject *res, *op;
1920
1921 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1922 return NULL;
1923 op = refchain._ob_next;
1924 res = PyList_New(0);
1925 if (res == NULL)
1926 return NULL;
1927 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1928 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001929 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001930 op = op->_ob_next;
1931 if (op == &refchain)
1932 return res;
1933 }
1934 if (PyList_Append(res, op) < 0) {
1935 Py_DECREF(res);
1936 return NULL;
1937 }
1938 op = op->_ob_next;
1939 }
1940 return res;
1941}
1942
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001943#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001944
1945
1946/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001947PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001948
1949
1950/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001951int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001952
1953
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001954/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001955
Thomas Wouters334fb892000-07-25 12:56:38 +00001956void *
Fred Drake100814d2000-07-09 15:48:49 +00001957PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001958{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001959 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001960}
1961
Thomas Wouters334fb892000-07-25 12:56:38 +00001962void *
1963PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001964{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001965 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001966}
1967
1968void
Thomas Wouters334fb892000-07-25 12:56:38 +00001969PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001970{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001971 PyMem_FREE(p);
1972}
1973
1974
Guido van Rossum86610361998-04-10 22:32:46 +00001975/* These methods are used to control infinite recursion in repr, str, print,
1976 etc. Container objects that may recursively contain themselves,
1977 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1978 Py_ReprLeave() to avoid infinite recursion.
1979
1980 Py_ReprEnter() returns 0 the first time it is called for a particular
1981 object and 1 every time thereafter. It returns -1 if an exception
1982 occurred. Py_ReprLeave() has no return value.
1983
1984 See dictobject.c and listobject.c for examples of use.
1985*/
1986
1987#define KEY "Py_Repr"
1988
1989int
Fred Drake100814d2000-07-09 15:48:49 +00001990Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001991{
1992 PyObject *dict;
1993 PyObject *list;
1994 int i;
1995
1996 dict = PyThreadState_GetDict();
1997 if (dict == NULL)
1998 return -1;
1999 list = PyDict_GetItemString(dict, KEY);
2000 if (list == NULL) {
2001 list = PyList_New(0);
2002 if (list == NULL)
2003 return -1;
2004 if (PyDict_SetItemString(dict, KEY, list) < 0)
2005 return -1;
2006 Py_DECREF(list);
2007 }
2008 i = PyList_GET_SIZE(list);
2009 while (--i >= 0) {
2010 if (PyList_GET_ITEM(list, i) == obj)
2011 return 1;
2012 }
2013 PyList_Append(list, obj);
2014 return 0;
2015}
2016
2017void
Fred Drake100814d2000-07-09 15:48:49 +00002018Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002019{
2020 PyObject *dict;
2021 PyObject *list;
2022 int i;
2023
2024 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002025 if (dict == NULL)
2026 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002027 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002028 if (list == NULL || !PyList_Check(list))
2029 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002030 i = PyList_GET_SIZE(list);
2031 /* Count backwards because we always expect obj to be list[-1] */
2032 while (--i >= 0) {
2033 if (PyList_GET_ITEM(list, i) == obj) {
2034 PyList_SetSlice(list, i, i + 1, NULL);
2035 break;
2036 }
2037 }
2038}
Guido van Rossumd724b232000-03-13 16:01:29 +00002039
Tim Peters803526b2002-07-07 05:13:56 +00002040/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002041
Tim Peters803526b2002-07-07 05:13:56 +00002042/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002043int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002044
Tim Peters803526b2002-07-07 05:13:56 +00002045/* List of objects that still need to be cleaned up, singly linked via their
2046 * gc headers' gc_prev pointers.
2047 */
2048PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002049
Tim Peters803526b2002-07-07 05:13:56 +00002050/* Add op to the _PyTrash_delete_later list. Called when the current
2051 * call-stack depth gets large. op must be a currently untracked gc'ed
2052 * object, with refcount 0. Py_DECREF must already have been called on it.
2053 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002054void
Fred Drake100814d2000-07-09 15:48:49 +00002055_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002056{
Tim Peters803526b2002-07-07 05:13:56 +00002057 assert(PyObject_IS_GC(op));
2058 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2059 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002060 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002061 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002062}
2063
Tim Peters803526b2002-07-07 05:13:56 +00002064/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2065 * the call-stack unwinds again.
2066 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002067void
Fred Drake100814d2000-07-09 15:48:49 +00002068_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002069{
2070 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002071 PyObject *op = _PyTrash_delete_later;
2072 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002073
Neil Schemenauerf589c052002-03-29 03:05:54 +00002074 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002075 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002076
Tim Peters803526b2002-07-07 05:13:56 +00002077 /* Call the deallocator directly. This used to try to
2078 * fool Py_DECREF into calling it indirectly, but
2079 * Py_DECREF was already called on this object, and in
2080 * assorted non-release builds calling Py_DECREF again ends
2081 * up distorting allocation statistics.
2082 */
2083 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002084 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002085 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002086 --_PyTrash_delete_nesting;
2087 }
2088}