blob: 1283294a060e5d817974afab19f66bf081e160b7 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jack Jansen28fc8802000-07-11 21:47:20 +00006#ifdef macintosh
7#include "macglue.h"
8#endif
9
Tim Peters34592512002-07-11 06:23:50 +000010#ifdef Py_REF_DEBUG
Mark Hammonda2905272002-07-29 13:42:14 +000011long _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Mark Hammonda2905272002-07-29 13:42:14 +000014int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000015
Guido van Rossum3f5da241990-12-20 15:06:42 +000016/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
17 These are used by the individual routines for object creation.
18 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000019
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000020#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000022extern int tuple_zero_allocs, fast_tuple_allocs;
23extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000024extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000025void
Fred Drake100814d2000-07-09 15:48:49 +000026dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000027{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000028 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000029
30 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000031 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000032 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000033 tp->tp_maxalloc);
34 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
35 fast_tuple_allocs, tuple_zero_allocs);
36 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
37 quick_int_allocs, quick_neg_int_allocs);
38 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
39 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000040}
41
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000042PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000043get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000044{
45 PyTypeObject *tp;
46 PyObject *result;
47 PyObject *v;
48
49 result = PyList_New(0);
50 if (result == NULL)
51 return NULL;
52 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000053 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
54 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000055 if (v == NULL) {
56 Py_DECREF(result);
57 return NULL;
58 }
59 if (PyList_Append(result, v) < 0) {
60 Py_DECREF(v);
61 Py_DECREF(result);
62 return NULL;
63 }
64 Py_DECREF(v);
65 }
66 return result;
67}
68
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000069void
Fred Drake100814d2000-07-09 15:48:49 +000070inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000071{
Tim Peters6d6c1a32001-08-02 04:15:00 +000072 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +000073 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +000077 /* Note that as of Python 2.2, heap-allocated type objects
78 * can go away, but this code requires that they stay alive
79 * until program exit. That's why we're careful with
80 * refcounts here. type_list gets a new reference to tp,
81 * while ownership of the reference type_list used to hold
82 * (if any) was transferred to tp->tp_next in the line above.
83 * tp is thus effectively immortal after this.
84 */
85 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000086 type_list = tp;
87 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000088 tp->tp_allocs++;
89 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
90 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000091}
92#endif
93
Tim Peters7c321a82002-07-09 02:57:01 +000094#ifdef Py_REF_DEBUG
95/* Log a fatal error; doesn't return. */
96void
97_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
98{
99 char buf[300];
100
101 PyOS_snprintf(buf, sizeof(buf),
102 "%s:%i object at %p has negative ref count %i",
103 fname, lineno, op, op->ob_refcnt);
104 Py_FatalError(buf);
105}
106
107#endif /* Py_REF_DEBUG */
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000110PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000112 if (op == NULL) {
113 PyErr_SetString(PyExc_SystemError,
114 "NULL object passed to PyObject_Init");
115 return op;
116 }
117 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000118 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000119 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000120 return op;
121}
122
Guido van Rossumb18618d2000-05-03 23:44:39 +0000123PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000124PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000125{
126 if (op == NULL) {
127 PyErr_SetString(PyExc_SystemError,
128 "NULL object passed to PyObject_InitVar");
129 return op;
130 }
131 /* Any changes should be reflected in PyObject_INIT_VAR */
132 op->ob_size = size;
133 op->ob_type = tp;
134 _Py_NewReference((PyObject *)op);
135 return op;
136}
137
138PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000139_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000140{
141 PyObject *op;
142 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
143 if (op == NULL)
144 return PyErr_NoMemory();
145 return PyObject_INIT(op, tp);
146}
147
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000148PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000149_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000151 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000152 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000153 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000155 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000156 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157}
158
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000159/* for binary compatibility with 2.2 */
160#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000161void
Fred Drake100814d2000-07-09 15:48:49 +0000162_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000163{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000164 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165}
166
Guido van Rossum90933611991-06-07 16:10:43 +0000167int
Fred Drake100814d2000-07-09 15:48:49 +0000168PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169{
Guido van Rossum278ef591991-07-27 21:40:24 +0000170 int ret = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000172 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000173#ifdef USE_STACKCHECK
174 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000175 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000176 return -1;
177 }
178#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000179 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000180 if (op == NULL) {
181 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000182 }
Guido van Rossum90933611991-06-07 16:10:43 +0000183 else {
184 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000185 fprintf(fp, "<refcnt %u at %p>",
186 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000187 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000188 PyObject *s;
189 if (flags & Py_PRINT_RAW)
190 s = PyObject_Str(op);
191 else
192 s = PyObject_Repr(op);
193 if (s == NULL)
194 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000195 else {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000196 ret = PyObject_Print(s, fp, Py_PRINT_RAW);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000197 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000198 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000199 }
Guido van Rossum90933611991-06-07 16:10:43 +0000200 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000201 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000202 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000203 if (ret == 0) {
204 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000206 clearerr(fp);
207 ret = -1;
208 }
209 }
210 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211}
212
Barry Warsaw9bf16442001-01-23 16:24:35 +0000213/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000214void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000215{
Barry Warsaweefb1072001-02-22 22:39:18 +0000216 if (op == NULL)
217 fprintf(stderr, "NULL\n");
218 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000219 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000220 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000221 fprintf(stderr, "\n"
222 "type : %s\n"
223 "refcount: %d\n"
224 "address : %p\n",
225 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
226 op->ob_refcnt,
227 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000228 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000229}
Barry Warsaw903138f2001-01-23 16:33:18 +0000230
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000232PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000235 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000236#ifdef USE_STACKCHECK
237 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000238 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000239 return NULL;
240 }
241#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000242 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000244 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000245 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000246 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000247 else {
248 PyObject *res;
249 res = (*v->ob_type->tp_repr)(v);
250 if (res == NULL)
251 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000252#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000253 if (PyUnicode_Check(res)) {
254 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000255 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000256 Py_DECREF(res);
257 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000258 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000259 else
260 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000261 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000262#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000263 if (!PyString_Check(res)) {
264 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000265 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000266 res->ob_type->tp_name);
267 Py_DECREF(res);
268 return NULL;
269 }
270 return res;
271 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272}
273
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000275PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000276{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000277 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000278
Guido van Rossumc6004111993-11-05 10:22:19 +0000279 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000280 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000281 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000283 return v;
284 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000285 if (v->ob_type->tp_str == NULL)
286 return PyObject_Repr(v);
287
288 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000289 if (res == NULL)
290 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000291#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000292 if (PyUnicode_Check(res)) {
293 PyObject* str;
294 str = PyUnicode_AsEncodedString(res, NULL, NULL);
295 Py_DECREF(res);
296 if (str)
297 res = str;
298 else
299 return NULL;
300 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000301#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000302 if (!PyString_Check(res)) {
303 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000304 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000305 res->ob_type->tp_name);
306 Py_DECREF(res);
307 return NULL;
308 }
309 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000310}
311
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000312#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000313PyObject *
314PyObject_Unicode(PyObject *v)
315{
316 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000317
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000318 if (v == NULL)
319 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000320 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000321 Py_INCREF(v);
322 return v;
323 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000324 if (PyUnicode_Check(v)) {
325 /* For a Unicode subtype that's not a Unicode object,
326 return a true Unicode object with the same data. */
327 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
328 PyUnicode_GET_SIZE(v));
329 }
330 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000331 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000332 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000333 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000334 else {
335 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000336 static PyObject *unicodestr;
337 /* XXX As soon as we have a tp_unicode slot, we should
338 check this before trying the __unicode__
339 method. */
340 if (unicodestr == NULL) {
341 unicodestr= PyString_InternFromString(
342 "__unicode__");
343 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000344 return NULL;
345 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000346 func = PyObject_GetAttr(v, unicodestr);
347 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000348 res = PyEval_CallObject(func, (PyObject *)NULL);
349 Py_DECREF(func);
350 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000351 else {
352 PyErr_Clear();
353 if (v->ob_type->tp_str != NULL)
354 res = (*v->ob_type->tp_str)(v);
355 else
356 res = PyObject_Repr(v);
357 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000358 }
359 if (res == NULL)
360 return NULL;
361 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000362 PyObject *str;
363 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000364 Py_DECREF(res);
365 if (str)
366 res = str;
367 else
368 return NULL;
369 }
370 return res;
371}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000372#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000373
374
Guido van Rossuma4073002002-05-31 20:03:54 +0000375/* Helper to warn about deprecated tp_compare return values. Return:
376 -2 for an exception;
377 -1 if v < w;
378 0 if v == w;
379 1 if v > w.
380 (This function cannot return 2.)
381*/
382static int
383adjust_tp_compare(int c)
384{
385 if (PyErr_Occurred()) {
386 if (c != -1 && c != -2) {
387 PyObject *t, *v, *tb;
388 PyErr_Fetch(&t, &v, &tb);
389 if (PyErr_Warn(PyExc_RuntimeWarning,
390 "tp_compare didn't return -1 or -2 "
391 "for exception") < 0) {
392 Py_XDECREF(t);
393 Py_XDECREF(v);
394 Py_XDECREF(tb);
395 }
396 else
397 PyErr_Restore(t, v, tb);
398 }
399 return -2;
400 }
401 else if (c < -1 || c > 1) {
402 if (PyErr_Warn(PyExc_RuntimeWarning,
403 "tp_compare didn't return -1, 0 or 1") < 0)
404 return -2;
405 else
406 return c < -1 ? -1 : 1;
407 }
408 else {
409 assert(c >= -1 && c <= 1);
410 return c;
411 }
412}
413
414
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000415/* Macro to get the tp_richcompare field of a type if defined */
416#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
417 ? (t)->tp_richcompare : NULL)
418
Guido van Rossume797ec12001-01-17 15:24:28 +0000419/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
420static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000421
Guido van Rossume797ec12001-01-17 15:24:28 +0000422/* Try a genuine rich comparison, returning an object. Return:
423 NULL for exception;
424 NotImplemented if this particular rich comparison is not implemented or
425 undefined;
426 some object not equal to NotImplemented if it is implemented
427 (this latter object may not be a Boolean).
428*/
429static PyObject *
430try_rich_compare(PyObject *v, PyObject *w, int op)
431{
432 richcmpfunc f;
433 PyObject *res;
434
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000435 if (v->ob_type != w->ob_type &&
436 PyType_IsSubtype(w->ob_type, v->ob_type) &&
437 (f = RICHCOMPARE(w->ob_type)) != NULL) {
438 res = (*f)(w, v, swapped_op[op]);
439 if (res != Py_NotImplemented)
440 return res;
441 Py_DECREF(res);
442 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000443 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000444 res = (*f)(v, w, op);
445 if (res != Py_NotImplemented)
446 return res;
447 Py_DECREF(res);
448 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000449 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000450 return (*f)(w, v, swapped_op[op]);
451 }
452 res = Py_NotImplemented;
453 Py_INCREF(res);
454 return res;
455}
456
457/* Try a genuine rich comparison, returning an int. Return:
458 -1 for exception (including the case where try_rich_compare() returns an
459 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000460 0 if the outcome is false;
461 1 if the outcome is true;
462 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000463*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000464static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000465try_rich_compare_bool(PyObject *v, PyObject *w, int op)
466{
467 PyObject *res;
468 int ok;
469
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000470 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000471 return 2; /* Shortcut, avoid INCREF+DECREF */
472 res = try_rich_compare(v, w, op);
473 if (res == NULL)
474 return -1;
475 if (res == Py_NotImplemented) {
476 Py_DECREF(res);
477 return 2;
478 }
479 ok = PyObject_IsTrue(res);
480 Py_DECREF(res);
481 return ok;
482}
483
484/* Try rich comparisons to determine a 3-way comparison. Return:
485 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000486 -1 if v < w;
487 0 if v == w;
488 1 if v > w;
489 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000490*/
491static int
492try_rich_to_3way_compare(PyObject *v, PyObject *w)
493{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000494 static struct { int op; int outcome; } tries[3] = {
495 /* Try this operator, and if it is true, use this outcome: */
496 {Py_EQ, 0},
497 {Py_LT, -1},
498 {Py_GT, 1},
499 };
500 int i;
501
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000502 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000503 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000504
505 for (i = 0; i < 3; i++) {
506 switch (try_rich_compare_bool(v, w, tries[i].op)) {
507 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000508 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000509 case 1:
510 return tries[i].outcome;
511 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000512 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000513
514 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000515}
516
517/* Try a 3-way comparison, returning an int. Return:
518 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000519 -1 if v < w;
520 0 if v == w;
521 1 if v > w;
522 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000523*/
524static int
525try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000526{
527 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000528 cmpfunc f;
529
530 /* Comparisons involving instances are given to instance_compare,
531 which has the same return conventions as this function. */
532
Guido van Rossumab3b0342001-09-18 20:38:53 +0000533 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000534 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000535 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000536 if (PyInstance_Check(w))
537 return (*w->ob_type->tp_compare)(v, w);
538
Guido van Rossumab3b0342001-09-18 20:38:53 +0000539 /* If both have the same (non-NULL) tp_compare, use it. */
540 if (f != NULL && f == w->ob_type->tp_compare) {
541 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000542 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000543 }
544
545 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
546 if (f == _PyObject_SlotCompare ||
547 w->ob_type->tp_compare == _PyObject_SlotCompare)
548 return _PyObject_SlotCompare(v, w);
549
Guido van Rossume797ec12001-01-17 15:24:28 +0000550 /* Try coercion; if it fails, give up */
551 c = PyNumber_CoerceEx(&v, &w);
552 if (c < 0)
553 return -2;
554 if (c > 0)
555 return 2;
556
557 /* Try v's comparison, if defined */
558 if ((f = v->ob_type->tp_compare) != NULL) {
559 c = (*f)(v, w);
560 Py_DECREF(v);
561 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000562 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000563 }
564
565 /* Try w's comparison, if defined */
566 if ((f = w->ob_type->tp_compare) != NULL) {
567 c = (*f)(w, v); /* swapped! */
568 Py_DECREF(v);
569 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000570 c = adjust_tp_compare(c);
571 if (c >= -1)
572 return -c; /* Swapped! */
573 else
574 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000575 }
576
577 /* No comparison defined */
578 Py_DECREF(v);
579 Py_DECREF(w);
580 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000581}
582
Guido van Rossume797ec12001-01-17 15:24:28 +0000583/* Final fallback 3-way comparison, returning an int. Return:
584 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000585 -1 if v < w;
586 0 if v == w;
587 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000588*/
589static int
590default_3way_compare(PyObject *v, PyObject *w)
591{
592 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000593 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000594
595 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000596 /* When comparing these pointers, they must be cast to
597 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
598 * uintptr_t). ANSI specifies that pointer compares other
599 * than == and != to non-related structures are undefined.
600 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000601 Py_uintptr_t vv = (Py_uintptr_t)v;
602 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000603 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
604 }
605
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000606#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000607 /* Special case for Unicode */
608 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
609 c = PyUnicode_Compare(v, w);
610 if (!PyErr_Occurred())
611 return c;
612 /* TypeErrors are ignored: if Unicode coercion fails due
613 to one of the arguments not having the right type, we
614 continue as defined by the coercion protocol (see
615 above). Luckily, decoding errors are reported as
616 ValueErrors and are not masked by this technique. */
617 if (!PyErr_ExceptionMatches(PyExc_TypeError))
618 return -2;
619 PyErr_Clear();
620 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000621#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000622
Guido van Rossum0871e932001-01-22 19:28:09 +0000623 /* None is smaller than anything */
624 if (v == Py_None)
625 return -1;
626 if (w == Py_None)
627 return 1;
628
Guido van Rossume797ec12001-01-17 15:24:28 +0000629 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000630 if (v->ob_type->tp_as_number)
631 vname = "";
632 else
633 vname = v->ob_type->tp_name;
634 if (w->ob_type->tp_as_number)
635 wname = "";
636 else
637 wname = w->ob_type->tp_name;
638 c = strcmp(vname, wname);
639 if (c < 0)
640 return -1;
641 if (c > 0)
642 return 1;
643 /* Same type name, or (more likely) incomparable numeric types */
644 return ((Py_uintptr_t)(v->ob_type) < (
645 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000646}
647
648#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
649
Tim Peters6d60b2e2001-05-07 20:53:51 +0000650/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000651 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000652 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000653 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000654 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000655 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000656 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000657*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000658static int
Fred Drake100814d2000-07-09 15:48:49 +0000659do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000660{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000661 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000662 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000663
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000664 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000665 && (f = v->ob_type->tp_compare) != NULL) {
666 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000667 if (PyInstance_Check(v)) {
668 /* Instance tp_compare has a different signature.
669 But if it returns undefined we fall through. */
670 if (c != 2)
671 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000672 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000673 }
674 else
675 return adjust_tp_compare(c);
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000676 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000677 /* We only get here if one of the following is true:
678 a) v and w have different types
679 b) v and w have the same type, which doesn't have tp_compare
680 c) v and w are instances, and either __cmp__ is not defined or
681 __cmp__ returns NotImplemented
682 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000683 c = try_rich_to_3way_compare(v, w);
684 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000685 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000686 c = try_3way_compare(v, w);
687 if (c < 2)
688 return c;
689 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000690}
691
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000692/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000693 some types) and decremented on exit. If the count exceeds the
694 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000695
696 This is a tunable parameter that should only affect the performance
697 of comparisons, nothing else. Setting it high makes comparing deeply
698 nested non-cyclical data structures faster, but makes comparing cyclical
699 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000700*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000701#define NESTING_LIMIT 20
702
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000703static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000704
705static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000706get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000707{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000708 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000709 PyObject *tstate_dict, *inprogress;
710
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000711 if (key == NULL) {
712 key = PyString_InternFromString("cmp_state");
713 if (key == NULL)
714 return NULL;
715 }
716
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000717 tstate_dict = PyThreadState_GetDict();
718 if (tstate_dict == NULL) {
719 PyErr_BadInternalCall();
720 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000721 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000722
Tim Peters803526b2002-07-07 05:13:56 +0000723 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000724 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000725 inprogress = PyDict_New();
726 if (inprogress == NULL)
727 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000728 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000729 Py_DECREF(inprogress);
730 return NULL;
731 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000732 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000733 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000734
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000735 return inprogress;
736}
737
738static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000739check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000740{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000741 PyObject *inprogress;
742 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000743 Py_uintptr_t iv = (Py_uintptr_t)v;
744 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000745 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000746
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000747 inprogress = get_inprogress_dict();
748 if (inprogress == NULL)
749 return NULL;
750
751 token = PyTuple_New(3);
752 if (token == NULL)
753 return NULL;
754
755 if (iv <= iw) {
756 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
757 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
758 if (op >= 0)
759 op = swapped_op[op];
760 } else {
761 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
762 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
763 }
764 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
765 if (x == NULL || y == NULL || z == NULL) {
766 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000767 return NULL;
768 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000769
770 if (PyDict_GetItem(inprogress, token) != NULL) {
771 Py_DECREF(token);
772 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000773 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000774
775 if (PyDict_SetItem(inprogress, token, token) < 0) {
776 Py_DECREF(token);
777 return NULL;
778 }
779
780 return token;
781}
782
783static void
784delete_token(PyObject *token)
785{
786 PyObject *inprogress;
787
788 if (token == NULL || token == Py_None)
789 return;
790 inprogress = get_inprogress_dict();
791 if (inprogress == NULL)
792 PyErr_Clear();
793 else
794 PyDict_DelItem(inprogress, token);
795 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000796}
797
Tim Petersc99213f2001-11-04 05:57:16 +0000798/* Compare v to w. Return
799 -1 if v < w or exception (PyErr_Occurred() true in latter case).
800 0 if v == w.
801 1 if v > w.
802 XXX The docs (C API manual) say the return value is undefined in case
803 XXX of error.
804*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805int
Fred Drake100814d2000-07-09 15:48:49 +0000806PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000807{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000808 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000809 int result;
810
Jack Jansend49cbe12000-08-22 21:52:51 +0000811#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000812 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000813 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000814 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000815 }
816#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000817 if (v == NULL || w == NULL) {
818 PyErr_BadInternalCall();
819 return -1;
820 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821 if (v == w)
822 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000823 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000824 compare_nesting++;
825 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000826 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000827 || (vtp->tp_as_sequence
828 && !PyString_Check(v)
829 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000830 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000831 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000832
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000833 if (token == NULL) {
834 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000835 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000836 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000837 /* already comparing these objects. assume
838 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000839 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000840 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000841 else {
842 result = do_cmp(v, w);
843 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000844 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000845 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000846 else {
847 result = do_cmp(v, w);
848 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000849 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000850 return result < 0 ? -1 : result;
851}
852
Tim Petersc99213f2001-11-04 05:57:16 +0000853/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000854static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000855convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000856{
Guido van Rossume797ec12001-01-17 15:24:28 +0000857 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000858 switch (op) {
859 case Py_LT: c = c < 0; break;
860 case Py_LE: c = c <= 0; break;
861 case Py_EQ: c = c == 0; break;
862 case Py_NE: c = c != 0; break;
863 case Py_GT: c = c > 0; break;
864 case Py_GE: c = c >= 0; break;
865 }
866 result = c ? Py_True : Py_False;
867 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000868 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000869}
Tim Peters803526b2002-07-07 05:13:56 +0000870
Tim Petersc99213f2001-11-04 05:57:16 +0000871/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
872 Return
873 NULL if error
874 Py_True if v op w
875 Py_False if not (v op w)
876*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000877static PyObject *
878try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
879{
880 int c;
881
882 c = try_3way_compare(v, w);
883 if (c >= 2)
884 c = default_3way_compare(v, w);
885 if (c <= -2)
886 return NULL;
887 return convert_3way_to_object(op, c);
888}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000889
Tim Petersc99213f2001-11-04 05:57:16 +0000890/* Do rich comparison on v and w. Return
891 NULL if error
892 Else a new reference to an object other than Py_NotImplemented, usually(?):
893 Py_True if v op w
894 Py_False if not (v op w)
895*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000896static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000897do_richcmp(PyObject *v, PyObject *w, int op)
898{
899 PyObject *res;
900
901 res = try_rich_compare(v, w, op);
902 if (res != Py_NotImplemented)
903 return res;
904 Py_DECREF(res);
905
906 return try_3way_to_rich_compare(v, w, op);
907}
908
Tim Petersc99213f2001-11-04 05:57:16 +0000909/* Return:
910 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000911 some object not equal to NotImplemented if it is implemented
912 (this latter object may not be a Boolean).
913*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000914PyObject *
915PyObject_RichCompare(PyObject *v, PyObject *w, int op)
916{
917 PyObject *res;
918
919 assert(Py_LT <= op && op <= Py_GE);
920
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000921 compare_nesting++;
922 if (compare_nesting > NESTING_LIMIT &&
923 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000924 || (v->ob_type->tp_as_sequence
925 && !PyString_Check(v)
926 && !PyTuple_Check(v)))) {
Tim Peters67754e92001-11-04 07:29:31 +0000927
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000928 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000929 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000930 if (token == NULL) {
931 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000932 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000933 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000934 else if (token == Py_None) {
935 /* already comparing these objects with this operator.
936 assume they're equal until shown otherwise */
937 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000938 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000939 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000940 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000941 else {
942 PyErr_SetString(PyExc_ValueError,
943 "can't order recursive values");
944 res = NULL;
945 }
946 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000947 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000948 else {
949 res = do_richcmp(v, w, op);
950 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000951 }
Tim Peters67754e92001-11-04 07:29:31 +0000952 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000953 }
Tim Peters67754e92001-11-04 07:29:31 +0000954
955 /* No nesting extremism.
956 If the types are equal, and not old-style instances, try to
957 get out cheap (don't bother with coercions etc.). */
958 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
959 cmpfunc fcmp;
960 richcmpfunc frich = RICHCOMPARE(v->ob_type);
961 /* If the type has richcmp, try it first. try_rich_compare
962 tries it two-sided, which is not needed since we've a
963 single type only. */
964 if (frich != NULL) {
965 res = (*frich)(v, w, op);
966 if (res != Py_NotImplemented)
967 goto Done;
968 Py_DECREF(res);
969 }
970 /* No richcmp, or this particular richmp not implemented.
971 Try 3-way cmp. */
972 fcmp = v->ob_type->tp_compare;
973 if (fcmp != NULL) {
974 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000975 c = adjust_tp_compare(c);
976 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000977 res = NULL;
978 goto Done;
979 }
980 res = convert_3way_to_object(op, c);
981 goto Done;
982 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000983 }
Tim Peters67754e92001-11-04 07:29:31 +0000984
985 /* Fast path not taken, or couldn't deliver a useful result. */
986 res = do_richcmp(v, w, op);
987Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000988 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000989 return res;
990}
991
Tim Petersde9725f2001-05-05 10:06:17 +0000992/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000993int
994PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
995{
996 PyObject *res = PyObject_RichCompare(v, w, op);
997 int ok;
998
999 if (res == NULL)
1000 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +00001001 if (PyBool_Check(res))
1002 ok = (res == Py_True);
1003 else
1004 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +00001005 Py_DECREF(res);
1006 return ok;
1007}
Fred Drake13634cf2000-06-29 19:17:04 +00001008
1009/* Set of hash utility functions to help maintaining the invariant that
1010 iff a==b then hash(a)==hash(b)
1011
1012 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1013*/
1014
1015long
Fred Drake100814d2000-07-09 15:48:49 +00001016_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001017{
Tim Peters39dce292000-08-15 03:34:48 +00001018 double intpart, fractpart;
1019 int expo;
1020 long hipart;
1021 long x; /* the final hash value */
1022 /* This is designed so that Python numbers of different types
1023 * that compare equal hash to the same value; otherwise comparisons
1024 * of mapping keys will turn out weird.
1025 */
1026
1027#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1028{
1029 extended e;
1030 fractpart = modf(v, &e);
1031 intpart = e;
1032}
1033#else
1034 fractpart = modf(v, &intpart);
1035#endif
1036 if (fractpart == 0.0) {
1037 /* This must return the same hash as an equal int or long. */
1038 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1039 /* Convert to long and use its hash. */
1040 PyObject *plong; /* converted to Python long */
1041 if (Py_IS_INFINITY(intpart))
1042 /* can't convert to long int -- arbitrary */
1043 v = v < 0 ? -271828.0 : 314159.0;
1044 plong = PyLong_FromDouble(v);
1045 if (plong == NULL)
1046 return -1;
1047 x = PyObject_Hash(plong);
1048 Py_DECREF(plong);
1049 return x;
1050 }
1051 /* Fits in a C long == a Python int, so is its own hash. */
1052 x = (long)intpart;
1053 if (x == -1)
1054 x = -2;
1055 return x;
1056 }
1057 /* The fractional part is non-zero, so we don't have to worry about
1058 * making this match the hash of some other type.
1059 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001060 * Since the VAX D double format has 56 mantissa bits, which is the
1061 * most of any double format in use, each of these parts may have as
1062 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001063 * So, assuming sizeof(long) >= 4, each part can be broken into two
1064 * longs; frexp and multiplication are used to do that.
1065 * Also, since the Cray double format has 15 exponent bits, which is
1066 * the most of any double format in use, shifting the exponent field
1067 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001068 */
Tim Peters39dce292000-08-15 03:34:48 +00001069 v = frexp(v, &expo);
1070 v *= 2147483648.0; /* 2**31 */
1071 hipart = (long)v; /* take the top 32 bits */
1072 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1073 x = hipart + (long)v + (expo << 15);
1074 if (x == -1)
1075 x = -2;
1076 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001077}
1078
1079long
Fred Drake100814d2000-07-09 15:48:49 +00001080_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001081{
1082#if SIZEOF_LONG >= SIZEOF_VOID_P
1083 return (long)p;
1084#else
1085 /* convert to a Python long and hash that */
1086 PyObject* longobj;
1087 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001088
Fred Drake13634cf2000-06-29 19:17:04 +00001089 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1090 x = -1;
1091 goto finally;
1092 }
1093 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001094
Fred Drake13634cf2000-06-29 19:17:04 +00001095finally:
1096 Py_XDECREF(longobj);
1097 return x;
1098#endif
1099}
1100
1101
Guido van Rossum9bfef441993-03-29 10:43:31 +00001102long
Fred Drake100814d2000-07-09 15:48:49 +00001103PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001104{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001105 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001106 if (tp->tp_hash != NULL)
1107 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001108 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001109 return _Py_HashPointer(v); /* Use address as hash value */
1110 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001111 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001112 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001113 return -1;
1114}
1115
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001116PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001117PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001118{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001119 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001120
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001122 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 w = PyString_InternFromString(name);
1124 if (w == NULL)
1125 return NULL;
1126 res = PyObject_GetAttr(v, w);
1127 Py_XDECREF(w);
1128 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001129}
1130
1131int
Fred Drake100814d2000-07-09 15:48:49 +00001132PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001133{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001134 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001135 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001136 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001137 return 1;
1138 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001139 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001140 return 0;
1141}
1142
1143int
Fred Drake100814d2000-07-09 15:48:49 +00001144PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001145{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001146 PyObject *s;
1147 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001148
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001150 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 s = PyString_InternFromString(name);
1152 if (s == NULL)
1153 return -1;
1154 res = PyObject_SetAttr(v, s, w);
1155 Py_XDECREF(s);
1156 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001157}
1158
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001159PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001160PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001161{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001162 PyTypeObject *tp = v->ob_type;
1163
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001164 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001165#ifdef Py_USING_UNICODE
1166 /* The Unicode to string conversion is done here because the
1167 existing tp_getattro slots expect a string object as name
1168 and we wouldn't want to break those. */
1169 if (PyUnicode_Check(name)) {
1170 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1171 if (name == NULL)
1172 return NULL;
1173 }
1174 else
1175#endif
1176 {
1177 PyErr_SetString(PyExc_TypeError,
1178 "attribute name must be string");
1179 return NULL;
1180 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001181 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 if (tp->tp_getattro != NULL)
1183 return (*tp->tp_getattro)(v, name);
1184 if (tp->tp_getattr != NULL)
1185 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1186 PyErr_Format(PyExc_AttributeError,
1187 "'%.50s' object has no attribute '%.400s'",
1188 tp->tp_name, PyString_AS_STRING(name));
1189 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001190}
1191
1192int
Fred Drake100814d2000-07-09 15:48:49 +00001193PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001194{
1195 PyObject *res = PyObject_GetAttr(v, name);
1196 if (res != NULL) {
1197 Py_DECREF(res);
1198 return 1;
1199 }
1200 PyErr_Clear();
1201 return 0;
1202}
1203
1204int
Fred Drake100814d2000-07-09 15:48:49 +00001205PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001206{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001207 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001208 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001209
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001210 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001211#ifdef Py_USING_UNICODE
1212 /* The Unicode to string conversion is done here because the
1213 existing tp_setattro slots expect a string object as name
1214 and we wouldn't want to break those. */
1215 if (PyUnicode_Check(name)) {
1216 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1217 if (name == NULL)
1218 return -1;
1219 }
Tim Peters803526b2002-07-07 05:13:56 +00001220 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001221#endif
1222 {
1223 PyErr_SetString(PyExc_TypeError,
1224 "attribute name must be string");
1225 return -1;
1226 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001227 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001228 else
1229 Py_INCREF(name);
1230
1231 PyString_InternInPlace(&name);
1232 if (tp->tp_setattro != NULL) {
1233 err = (*tp->tp_setattro)(v, name, value);
1234 Py_DECREF(name);
1235 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001236 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001237 if (tp->tp_setattr != NULL) {
1238 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1239 Py_DECREF(name);
1240 return err;
1241 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001242 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1244 PyErr_Format(PyExc_TypeError,
1245 "'%.100s' object has no attributes "
1246 "(%s .%.100s)",
1247 tp->tp_name,
1248 value==NULL ? "del" : "assign to",
1249 PyString_AS_STRING(name));
1250 else
1251 PyErr_Format(PyExc_TypeError,
1252 "'%.100s' object has only read-only attributes "
1253 "(%s .%.100s)",
1254 tp->tp_name,
1255 value==NULL ? "del" : "assign to",
1256 PyString_AS_STRING(name));
1257 return -1;
1258}
1259
1260/* Helper to get a pointer to an object's __dict__ slot, if any */
1261
1262PyObject **
1263_PyObject_GetDictPtr(PyObject *obj)
1264{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 long dictoffset;
1266 PyTypeObject *tp = obj->ob_type;
1267
1268 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1269 return NULL;
1270 dictoffset = tp->tp_dictoffset;
1271 if (dictoffset == 0)
1272 return NULL;
1273 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001274 int tsize;
1275 size_t size;
1276
1277 tsize = ((PyVarObject *)obj)->ob_size;
1278 if (tsize < 0)
1279 tsize = -tsize;
1280 size = _PyObject_VAR_SIZE(tp, tsize);
1281
Tim Peters6d483d32001-10-06 21:27:34 +00001282 dictoffset += (long)size;
1283 assert(dictoffset > 0);
1284 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285 }
1286 return (PyObject **) ((char *)obj + dictoffset);
1287}
1288
1289/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1290
1291PyObject *
1292PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1293{
1294 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001295 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001296 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001297 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001298 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 PyObject **dictptr;
1300
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001301 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001302#ifdef Py_USING_UNICODE
1303 /* The Unicode to string conversion is done here because the
1304 existing tp_setattro slots expect a string object as name
1305 and we wouldn't want to break those. */
1306 if (PyUnicode_Check(name)) {
1307 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1308 if (name == NULL)
1309 return NULL;
1310 }
Tim Peters803526b2002-07-07 05:13:56 +00001311 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001312#endif
1313 {
1314 PyErr_SetString(PyExc_TypeError,
1315 "attribute name must be string");
1316 return NULL;
1317 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001318 }
1319 else
1320 Py_INCREF(name);
1321
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001323 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001324 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325 }
1326
Guido van Rossum056fbf42002-08-19 19:22:50 +00001327 /* Inline _PyType_Lookup */
1328 {
1329 int i, n;
1330 PyObject *mro, *base, *dict;
1331
1332 /* Look in tp_dict of types in MRO */
1333 mro = tp->tp_mro;
1334 assert(mro != NULL);
1335 assert(PyTuple_Check(mro));
1336 n = PyTuple_GET_SIZE(mro);
1337 for (i = 0; i < n; i++) {
1338 base = PyTuple_GET_ITEM(mro, i);
1339 if (PyClass_Check(base))
1340 dict = ((PyClassObject *)base)->cl_dict;
1341 else {
1342 assert(PyType_Check(base));
1343 dict = ((PyTypeObject *)base)->tp_dict;
1344 }
1345 assert(dict && PyDict_Check(dict));
1346 descr = PyDict_GetItem(dict, name);
1347 if (descr != NULL)
1348 break;
1349 }
1350 }
1351
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352 f = NULL;
1353 if (descr != NULL) {
1354 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001355 if (f != NULL && PyDescr_IsData(descr)) {
1356 res = f(descr, obj, (PyObject *)obj->ob_type);
1357 goto done;
1358 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 }
1360
Guido van Rossumc66ff442002-08-19 16:50:48 +00001361 /* Inline _PyObject_GetDictPtr */
1362 dictoffset = tp->tp_dictoffset;
1363 if (dictoffset != 0) {
1364 PyObject *dict;
1365 if (dictoffset < 0) {
1366 int tsize;
1367 size_t size;
1368
1369 tsize = ((PyVarObject *)obj)->ob_size;
1370 if (tsize < 0)
1371 tsize = -tsize;
1372 size = _PyObject_VAR_SIZE(tp, tsize);
1373
1374 dictoffset += (long)size;
1375 assert(dictoffset > 0);
1376 assert(dictoffset % SIZEOF_VOID_P == 0);
1377 }
1378 dictptr = (PyObject **) ((char *)obj + dictoffset);
1379 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001380 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001381 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001382 if (res != NULL) {
1383 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001384 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001385 }
1386 }
1387 }
1388
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001389 if (f != NULL) {
1390 res = f(descr, obj, (PyObject *)obj->ob_type);
1391 goto done;
1392 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393
1394 if (descr != NULL) {
1395 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001396 res = descr;
1397 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001398 }
1399
1400 PyErr_Format(PyExc_AttributeError,
1401 "'%.50s' object has no attribute '%.400s'",
1402 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001403 done:
1404 Py_DECREF(name);
1405 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406}
1407
1408int
1409PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1410{
1411 PyTypeObject *tp = obj->ob_type;
1412 PyObject *descr;
1413 descrsetfunc f;
1414 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001415 int res = -1;
1416
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001417 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001418#ifdef Py_USING_UNICODE
1419 /* The Unicode to string conversion is done here because the
1420 existing tp_setattro slots expect a string object as name
1421 and we wouldn't want to break those. */
1422 if (PyUnicode_Check(name)) {
1423 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1424 if (name == NULL)
1425 return -1;
1426 }
Tim Peters803526b2002-07-07 05:13:56 +00001427 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001428#endif
1429 {
1430 PyErr_SetString(PyExc_TypeError,
1431 "attribute name must be string");
1432 return -1;
1433 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001434 }
1435 else
1436 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001437
1438 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001439 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001440 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441 }
1442
1443 descr = _PyType_Lookup(tp, name);
1444 f = NULL;
1445 if (descr != NULL) {
1446 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001447 if (f != NULL && PyDescr_IsData(descr)) {
1448 res = f(descr, obj, value);
1449 goto done;
1450 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001451 }
1452
1453 dictptr = _PyObject_GetDictPtr(obj);
1454 if (dictptr != NULL) {
1455 PyObject *dict = *dictptr;
1456 if (dict == NULL && value != NULL) {
1457 dict = PyDict_New();
1458 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001459 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001460 *dictptr = dict;
1461 }
1462 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001463 if (value == NULL)
1464 res = PyDict_DelItem(dict, name);
1465 else
1466 res = PyDict_SetItem(dict, name, value);
1467 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1468 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001469 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 }
1471 }
1472
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001473 if (f != NULL) {
1474 res = f(descr, obj, value);
1475 goto done;
1476 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477
1478 if (descr == NULL) {
1479 PyErr_Format(PyExc_AttributeError,
1480 "'%.50s' object has no attribute '%.400s'",
1481 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001482 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001483 }
1484
1485 PyErr_Format(PyExc_AttributeError,
1486 "'%.50s' object attribute '%.400s' is read-only",
1487 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001488 done:
1489 Py_DECREF(name);
1490 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001491}
1492
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001493/* Test a value used as condition, e.g., in a for or if statement.
1494 Return -1 if an error occurred */
1495
1496int
Fred Drake100814d2000-07-09 15:48:49 +00001497PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001498{
1499 int res;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001500 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001501 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001502 else if (v->ob_type->tp_as_number != NULL &&
1503 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001504 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001505 else if (v->ob_type->tp_as_mapping != NULL &&
1506 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001507 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001508 else if (v->ob_type->tp_as_sequence != NULL &&
1509 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001510 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1511 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001512 return 1;
1513 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001514}
1515
Tim Peters803526b2002-07-07 05:13:56 +00001516/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001517 Return -1 if an error occurred */
1518
1519int
Fred Drake100814d2000-07-09 15:48:49 +00001520PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001521{
1522 int res;
1523 res = PyObject_IsTrue(v);
1524 if (res < 0)
1525 return res;
1526 return res == 0;
1527}
1528
Guido van Rossum5524a591995-01-10 15:26:20 +00001529/* Coerce two numeric types to the "larger" one.
1530 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001531 Return value:
1532 -1 if an error occurred;
1533 0 if the coercion succeeded (and then the reference counts are increased);
1534 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001535*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001536int
Fred Drake100814d2000-07-09 15:48:49 +00001537PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001538{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001539 register PyObject *v = *pv;
1540 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001541 int res;
1542
Guido van Rossum517c7d42002-04-26 02:49:14 +00001543 /* Shortcut only for old-style types */
1544 if (v->ob_type == w->ob_type &&
1545 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1546 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001547 Py_INCREF(v);
1548 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001549 return 0;
1550 }
1551 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1552 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1553 if (res <= 0)
1554 return res;
1555 }
1556 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1557 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1558 if (res <= 0)
1559 return res;
1560 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001561 return 1;
1562}
1563
Guido van Rossume797ec12001-01-17 15:24:28 +00001564/* Coerce two numeric types to the "larger" one.
1565 Increment the reference count on each argument.
1566 Return -1 and raise an exception if no coercion is possible
1567 (and then no reference count is incremented).
1568*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001569int
Fred Drake100814d2000-07-09 15:48:49 +00001570PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001571{
1572 int err = PyNumber_CoerceEx(pv, pw);
1573 if (err <= 0)
1574 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001575 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001576 return -1;
1577}
1578
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001579
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001580/* Test whether an object can be called */
1581
1582int
Fred Drake100814d2000-07-09 15:48:49 +00001583PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001584{
1585 if (x == NULL)
1586 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001587 if (PyInstance_Check(x)) {
1588 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001589 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001590 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001591 return 0;
1592 }
1593 /* Could test recursively but don't, for fear of endless
1594 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001595 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001596 return 1;
1597 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001598 else {
1599 return x->ob_type->tp_call != NULL;
1600 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001601}
1602
Tim Peters7eea37e2001-09-04 22:08:56 +00001603/* Helper for PyObject_Dir.
1604 Merge the __dict__ of aclass into dict, and recursively also all
1605 the __dict__s of aclass's base classes. The order of merging isn't
1606 defined, as it's expected that only the final set of dict keys is
1607 interesting.
1608 Return 0 on success, -1 on error.
1609*/
1610
1611static int
1612merge_class_dict(PyObject* dict, PyObject* aclass)
1613{
1614 PyObject *classdict;
1615 PyObject *bases;
1616
1617 assert(PyDict_Check(dict));
1618 assert(aclass);
1619
1620 /* Merge in the type's dict (if any). */
1621 classdict = PyObject_GetAttrString(aclass, "__dict__");
1622 if (classdict == NULL)
1623 PyErr_Clear();
1624 else {
1625 int status = PyDict_Update(dict, classdict);
1626 Py_DECREF(classdict);
1627 if (status < 0)
1628 return -1;
1629 }
1630
1631 /* Recursively merge in the base types' (if any) dicts. */
1632 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001633 if (bases == NULL)
1634 PyErr_Clear();
1635 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001636 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001637 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001638 n = PySequence_Size(bases); /* This better be right */
1639 if (n < 0)
1640 PyErr_Clear();
1641 else {
1642 for (i = 0; i < n; i++) {
1643 PyObject *base = PySequence_GetItem(bases, i);
1644 if (base == NULL) {
1645 Py_DECREF(bases);
1646 return -1;
1647 }
1648 if (merge_class_dict(dict, base) < 0) {
1649 Py_DECREF(bases);
1650 return -1;
1651 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001652 }
1653 }
1654 Py_DECREF(bases);
1655 }
1656 return 0;
1657}
1658
Tim Peters305b5852001-09-17 02:38:46 +00001659/* Helper for PyObject_Dir.
1660 If obj has an attr named attrname that's a list, merge its string
1661 elements into keys of dict.
1662 Return 0 on success, -1 on error. Errors due to not finding the attr,
1663 or the attr not being a list, are suppressed.
1664*/
1665
1666static int
1667merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1668{
1669 PyObject *list;
1670 int result = 0;
1671
1672 assert(PyDict_Check(dict));
1673 assert(obj);
1674 assert(attrname);
1675
1676 list = PyObject_GetAttrString(obj, attrname);
1677 if (list == NULL)
1678 PyErr_Clear();
1679
1680 else if (PyList_Check(list)) {
1681 int i;
1682 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1683 PyObject *item = PyList_GET_ITEM(list, i);
1684 if (PyString_Check(item)) {
1685 result = PyDict_SetItem(dict, item, Py_None);
1686 if (result < 0)
1687 break;
1688 }
1689 }
1690 }
1691
1692 Py_XDECREF(list);
1693 return result;
1694}
1695
Tim Peters7eea37e2001-09-04 22:08:56 +00001696/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1697 docstring, which should be kept in synch with this implementation. */
1698
1699PyObject *
1700PyObject_Dir(PyObject *arg)
1701{
1702 /* Set exactly one of these non-NULL before the end. */
1703 PyObject *result = NULL; /* result list */
1704 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1705
1706 /* If NULL arg, return the locals. */
1707 if (arg == NULL) {
1708 PyObject *locals = PyEval_GetLocals();
1709 if (locals == NULL)
1710 goto error;
1711 result = PyDict_Keys(locals);
1712 if (result == NULL)
1713 goto error;
1714 }
1715
1716 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001717 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001718 masterdict = PyObject_GetAttrString(arg, "__dict__");
1719 if (masterdict == NULL)
1720 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001721 if (!PyDict_Check(masterdict)) {
1722 PyErr_SetString(PyExc_TypeError,
1723 "module.__dict__ is not a dictionary");
1724 goto error;
1725 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001726 }
1727
1728 /* Elif some form of type or class, grab its dict and its bases.
1729 We deliberately don't suck up its __class__, as methods belonging
1730 to the metaclass would probably be more confusing than helpful. */
1731 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1732 masterdict = PyDict_New();
1733 if (masterdict == NULL)
1734 goto error;
1735 if (merge_class_dict(masterdict, arg) < 0)
1736 goto error;
1737 }
1738
1739 /* Else look at its dict, and the attrs reachable from its class. */
1740 else {
1741 PyObject *itsclass;
1742 /* Create a dict to start with. CAUTION: Not everything
1743 responding to __dict__ returns a dict! */
1744 masterdict = PyObject_GetAttrString(arg, "__dict__");
1745 if (masterdict == NULL) {
1746 PyErr_Clear();
1747 masterdict = PyDict_New();
1748 }
1749 else if (!PyDict_Check(masterdict)) {
1750 Py_DECREF(masterdict);
1751 masterdict = PyDict_New();
1752 }
1753 else {
1754 /* The object may have returned a reference to its
1755 dict, so copy it to avoid mutating it. */
1756 PyObject *temp = PyDict_Copy(masterdict);
1757 Py_DECREF(masterdict);
1758 masterdict = temp;
1759 }
1760 if (masterdict == NULL)
1761 goto error;
1762
Tim Peters305b5852001-09-17 02:38:46 +00001763 /* Merge in __members__ and __methods__ (if any).
1764 XXX Would like this to go away someday; for now, it's
1765 XXX needed to get at im_self etc of method objects. */
1766 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1767 goto error;
1768 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1769 goto error;
1770
Tim Peters7eea37e2001-09-04 22:08:56 +00001771 /* Merge in attrs reachable from its class.
1772 CAUTION: Not all objects have a __class__ attr. */
1773 itsclass = PyObject_GetAttrString(arg, "__class__");
1774 if (itsclass == NULL)
1775 PyErr_Clear();
1776 else {
1777 int status = merge_class_dict(masterdict, itsclass);
1778 Py_DECREF(itsclass);
1779 if (status < 0)
1780 goto error;
1781 }
1782 }
1783
1784 assert((result == NULL) ^ (masterdict == NULL));
1785 if (masterdict != NULL) {
1786 /* The result comes from its keys. */
1787 assert(result == NULL);
1788 result = PyDict_Keys(masterdict);
1789 if (result == NULL)
1790 goto error;
1791 }
1792
1793 assert(result);
1794 if (PyList_Sort(result) != 0)
1795 goto error;
1796 else
1797 goto normal_return;
1798
1799 error:
1800 Py_XDECREF(result);
1801 result = NULL;
1802 /* fall through */
1803 normal_return:
1804 Py_XDECREF(masterdict);
1805 return result;
1806}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001807
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001808/*
1809NoObject is usable as a non-NULL undefined value, used by the macro None.
1810There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001811so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001812(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001813*/
1814
Guido van Rossum0c182a11992-03-27 17:26:13 +00001815/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001816static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001817none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001818{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001819 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001820}
1821
Barry Warsaw9bf16442001-01-23 16:24:35 +00001822/* ARGUSED */
1823static void
Tim Peters803526b2002-07-07 05:13:56 +00001824none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001825{
1826 /* This should never get called, but we also don't want to SEGV if
1827 * we accidently decref None out of existance.
1828 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001829 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001830}
1831
1832
Guido van Rossumba21a492001-08-16 08:17:26 +00001833static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001834 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001835 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001836 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001837 0,
1838 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001839 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001840 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001841 0, /*tp_getattr*/
1842 0, /*tp_setattr*/
1843 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001844 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001845 0, /*tp_as_number*/
1846 0, /*tp_as_sequence*/
1847 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001848 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001849};
1850
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001851PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001852 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853};
1854
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001855/* NotImplemented is an object that can be used to signal that an
1856 operation is not implemented for the given type combination. */
1857
1858static PyObject *
1859NotImplemented_repr(PyObject *op)
1860{
1861 return PyString_FromString("NotImplemented");
1862}
1863
1864static PyTypeObject PyNotImplemented_Type = {
1865 PyObject_HEAD_INIT(&PyType_Type)
1866 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001867 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001868 0,
1869 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001870 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001871 0, /*tp_print*/
1872 0, /*tp_getattr*/
1873 0, /*tp_setattr*/
1874 0, /*tp_compare*/
1875 (reprfunc)NotImplemented_repr, /*tp_repr*/
1876 0, /*tp_as_number*/
1877 0, /*tp_as_sequence*/
1878 0, /*tp_as_mapping*/
1879 0, /*tp_hash */
1880};
1881
1882PyObject _Py_NotImplementedStruct = {
1883 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1884};
1885
Guido van Rossumba21a492001-08-16 08:17:26 +00001886void
1887_Py_ReadyTypes(void)
1888{
1889 if (PyType_Ready(&PyType_Type) < 0)
1890 Py_FatalError("Can't initialize 'type'");
1891
Guido van Rossum77f6a652002-04-03 22:41:51 +00001892 if (PyType_Ready(&PyBool_Type) < 0)
1893 Py_FatalError("Can't initialize 'bool'");
1894
Guido van Rossumcacfc072002-05-24 19:01:59 +00001895 if (PyType_Ready(&PyString_Type) < 0)
1896 Py_FatalError("Can't initialize 'str'");
1897
Guido van Rossumba21a492001-08-16 08:17:26 +00001898 if (PyType_Ready(&PyList_Type) < 0)
1899 Py_FatalError("Can't initialize 'list'");
1900
1901 if (PyType_Ready(&PyNone_Type) < 0)
1902 Py_FatalError("Can't initialize type(None)");
1903
1904 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1905 Py_FatalError("Can't initialize type(NotImplemented)");
1906}
1907
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001908
Guido van Rossum84a90321996-05-22 16:34:47 +00001909#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001910
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001912
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001913void
Fred Drake100814d2000-07-09 15:48:49 +00001914_Py_ResetReferences(void)
Guido van Rossume09fb551997-08-05 02:04:34 +00001915{
1916 refchain._ob_prev = refchain._ob_next = &refchain;
1917 _Py_RefTotal = 0;
1918}
1919
1920void
Fred Drake100814d2000-07-09 15:48:49 +00001921_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001922{
Tim Peters34592512002-07-11 06:23:50 +00001923 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001924 op->ob_refcnt = 1;
1925 op->_ob_next = refchain._ob_next;
1926 op->_ob_prev = &refchain;
1927 refchain._ob_next->_ob_prev = op;
1928 refchain._ob_next = op;
Tim Peters34592512002-07-11 06:23:50 +00001929 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001930}
1931
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001932void
Fred Drake100814d2000-07-09 15:48:49 +00001933_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001934{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001935#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001936 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001937#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001938 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001939 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001940 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001941 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001942 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001943#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001944 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1945 if (p == op)
1946 break;
1947 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001948 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001949 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001950#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001951 op->_ob_next->_ob_prev = op->_ob_prev;
1952 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001953 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001954 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001955}
1956
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001957void
Fred Drake100814d2000-07-09 15:48:49 +00001958_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001959{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001960 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001961 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001962 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001963}
1964
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001965void
Fred Drake100814d2000-07-09 15:48:49 +00001966_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001967{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001968 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001969 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001970 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1971 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001972 if (PyObject_Print(op, fp, 0) != 0)
1973 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001974 putc('\n', fp);
1975 }
1976}
1977
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001978PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001979_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001980{
1981 int i, n;
1982 PyObject *t = NULL;
1983 PyObject *res, *op;
1984
1985 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1986 return NULL;
1987 op = refchain._ob_next;
1988 res = PyList_New(0);
1989 if (res == NULL)
1990 return NULL;
1991 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1992 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001993 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001994 op = op->_ob_next;
1995 if (op == &refchain)
1996 return res;
1997 }
1998 if (PyList_Append(res, op) < 0) {
1999 Py_DECREF(res);
2000 return NULL;
2001 }
2002 op = op->_ob_next;
2003 }
2004 return res;
2005}
2006
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002007#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002008
2009
2010/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00002011PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00002012
2013
2014/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00002015int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002016
2017
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00002018/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00002019
Thomas Wouters334fb892000-07-25 12:56:38 +00002020void *
Fred Drake100814d2000-07-09 15:48:49 +00002021PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002022{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002023 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002024}
2025
Thomas Wouters334fb892000-07-25 12:56:38 +00002026void *
2027PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002028{
Tim Petersaf3e8de2002-04-12 07:22:56 +00002029 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002030}
2031
2032void
Thomas Wouters334fb892000-07-25 12:56:38 +00002033PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002034{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002035 PyMem_FREE(p);
2036}
2037
2038
Guido van Rossum86610361998-04-10 22:32:46 +00002039/* These methods are used to control infinite recursion in repr, str, print,
2040 etc. Container objects that may recursively contain themselves,
2041 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2042 Py_ReprLeave() to avoid infinite recursion.
2043
2044 Py_ReprEnter() returns 0 the first time it is called for a particular
2045 object and 1 every time thereafter. It returns -1 if an exception
2046 occurred. Py_ReprLeave() has no return value.
2047
2048 See dictobject.c and listobject.c for examples of use.
2049*/
2050
2051#define KEY "Py_Repr"
2052
2053int
Fred Drake100814d2000-07-09 15:48:49 +00002054Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002055{
2056 PyObject *dict;
2057 PyObject *list;
2058 int i;
2059
2060 dict = PyThreadState_GetDict();
2061 if (dict == NULL)
2062 return -1;
2063 list = PyDict_GetItemString(dict, KEY);
2064 if (list == NULL) {
2065 list = PyList_New(0);
2066 if (list == NULL)
2067 return -1;
2068 if (PyDict_SetItemString(dict, KEY, list) < 0)
2069 return -1;
2070 Py_DECREF(list);
2071 }
2072 i = PyList_GET_SIZE(list);
2073 while (--i >= 0) {
2074 if (PyList_GET_ITEM(list, i) == obj)
2075 return 1;
2076 }
2077 PyList_Append(list, obj);
2078 return 0;
2079}
2080
2081void
Fred Drake100814d2000-07-09 15:48:49 +00002082Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002083{
2084 PyObject *dict;
2085 PyObject *list;
2086 int i;
2087
2088 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002089 if (dict == NULL)
2090 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002091 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002092 if (list == NULL || !PyList_Check(list))
2093 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002094 i = PyList_GET_SIZE(list);
2095 /* Count backwards because we always expect obj to be list[-1] */
2096 while (--i >= 0) {
2097 if (PyList_GET_ITEM(list, i) == obj) {
2098 PyList_SetSlice(list, i, i + 1, NULL);
2099 break;
2100 }
2101 }
2102}
Guido van Rossumd724b232000-03-13 16:01:29 +00002103
Tim Peters803526b2002-07-07 05:13:56 +00002104/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002105
Tim Peters803526b2002-07-07 05:13:56 +00002106/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002107int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002108
Tim Peters803526b2002-07-07 05:13:56 +00002109/* List of objects that still need to be cleaned up, singly linked via their
2110 * gc headers' gc_prev pointers.
2111 */
2112PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002113
Tim Peters803526b2002-07-07 05:13:56 +00002114/* Add op to the _PyTrash_delete_later list. Called when the current
2115 * call-stack depth gets large. op must be a currently untracked gc'ed
2116 * object, with refcount 0. Py_DECREF must already have been called on it.
2117 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002118void
Fred Drake100814d2000-07-09 15:48:49 +00002119_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002120{
Tim Peters803526b2002-07-07 05:13:56 +00002121 assert(PyObject_IS_GC(op));
2122 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2123 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002124 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002125 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002126}
2127
Tim Peters803526b2002-07-07 05:13:56 +00002128/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2129 * the call-stack unwinds again.
2130 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002131void
Fred Drake100814d2000-07-09 15:48:49 +00002132_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002133{
2134 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002135 PyObject *op = _PyTrash_delete_later;
2136 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002137
Neil Schemenauerf589c052002-03-29 03:05:54 +00002138 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002139 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002140
Tim Peters803526b2002-07-07 05:13:56 +00002141 /* Call the deallocator directly. This used to try to
2142 * fool Py_DECREF into calling it indirectly, but
2143 * Py_DECREF was already called on this object, and in
2144 * assorted non-release builds calling Py_DECREF again ends
2145 * up distorting allocation statistics.
2146 */
2147 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002148 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002149 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002150 --_PyTrash_delete_nesting;
2151 }
2152}