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