blob: e3234deca72dd5fded659606fba9577a3bd9b5e3 [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 Rossum6e08c142002-10-11 20:37:24 +0000112 if (op == NULL)
113 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000114 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117 return op;
118}
119
Guido van Rossumb18618d2000-05-03 23:44:39 +0000120PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000121PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000122{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000123 if (op == NULL)
124 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000125 /* Any changes should be reflected in PyObject_INIT_VAR */
126 op->ob_size = size;
127 op->ob_type = tp;
128 _Py_NewReference((PyObject *)op);
129 return op;
130}
131
132PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000133_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000134{
135 PyObject *op;
136 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
137 if (op == NULL)
138 return PyErr_NoMemory();
139 return PyObject_INIT(op, tp);
140}
141
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000142PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000143_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000145 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000146 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000147 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000149 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000150 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000151}
152
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000153/* for binary compatibility with 2.2 */
154#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000155void
Fred Drake100814d2000-07-09 15:48:49 +0000156_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000157{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000158 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Neal Norwitz1a997502003-01-13 20:13:12 +0000161/* Implementation of PyObject_Print with recursion checking */
162static int
163internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164{
Guido van Rossum278ef591991-07-27 21:40:24 +0000165 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000166 if (nesting > 10) {
167 PyErr_SetString(PyExc_RuntimeError, "print recursion");
168 return -1;
169 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000171 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000172#ifdef USE_STACKCHECK
173 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000174 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000175 return -1;
176 }
177#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000178 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000179 if (op == NULL) {
180 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181 }
Guido van Rossum90933611991-06-07 16:10:43 +0000182 else {
183 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000184 fprintf(fp, "<refcnt %u at %p>",
185 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000186 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000187 PyObject *s;
188 if (flags & Py_PRINT_RAW)
189 s = PyObject_Str(op);
190 else
191 s = PyObject_Repr(op);
192 if (s == NULL)
193 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000194 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000195 ret = internal_print(s, fp, Py_PRINT_RAW,
196 nesting+1);
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
Neal Norwitz1a997502003-01-13 20:13:12 +0000213int
214PyObject_Print(PyObject *op, FILE *fp, int flags)
215{
216 return internal_print(op, fp, flags, 0);
217}
218
219
Barry Warsaw9bf16442001-01-23 16:24:35 +0000220/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000221void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000222{
Barry Warsaweefb1072001-02-22 22:39:18 +0000223 if (op == NULL)
224 fprintf(stderr, "NULL\n");
225 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000226 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000227 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000228 fprintf(stderr, "\n"
229 "type : %s\n"
230 "refcount: %d\n"
231 "address : %p\n",
232 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
233 op->ob_refcnt,
234 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000235 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000236}
Barry Warsaw903138f2001-01-23 16:33:18 +0000237
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000239PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000241 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000242 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000243#ifdef USE_STACKCHECK
244 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000245 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000246 return NULL;
247 }
248#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000249 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000251 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000252 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000253 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000254 else {
255 PyObject *res;
256 res = (*v->ob_type->tp_repr)(v);
257 if (res == NULL)
258 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000259#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000260 if (PyUnicode_Check(res)) {
261 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000262 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000263 Py_DECREF(res);
264 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000265 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000266 else
267 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000268 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000269#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000270 if (!PyString_Check(res)) {
271 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000272 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000273 res->ob_type->tp_name);
274 Py_DECREF(res);
275 return NULL;
276 }
277 return res;
278 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279}
280
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000282PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000283{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000284 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000285
Guido van Rossumc6004111993-11-05 10:22:19 +0000286 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000287 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000288 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000289 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000290 return v;
291 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000292 if (v->ob_type->tp_str == NULL)
293 return PyObject_Repr(v);
294
295 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000296 if (res == NULL)
297 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000298#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000299 if (PyUnicode_Check(res)) {
300 PyObject* str;
301 str = PyUnicode_AsEncodedString(res, NULL, NULL);
302 Py_DECREF(res);
303 if (str)
304 res = str;
305 else
306 return NULL;
307 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000308#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000309 if (!PyString_Check(res)) {
310 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000311 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000312 res->ob_type->tp_name);
313 Py_DECREF(res);
314 return NULL;
315 }
316 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000317}
318
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000319#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000320PyObject *
321PyObject_Unicode(PyObject *v)
322{
323 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000324
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000325 if (v == NULL)
326 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000327 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000328 Py_INCREF(v);
329 return v;
330 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000331 if (PyUnicode_Check(v)) {
332 /* For a Unicode subtype that's not a Unicode object,
333 return a true Unicode object with the same data. */
334 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
335 PyUnicode_GET_SIZE(v));
336 }
337 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000338 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000339 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000340 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000341 else {
342 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000343 static PyObject *unicodestr;
344 /* XXX As soon as we have a tp_unicode slot, we should
345 check this before trying the __unicode__
346 method. */
347 if (unicodestr == NULL) {
348 unicodestr= PyString_InternFromString(
349 "__unicode__");
350 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000351 return NULL;
352 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000353 func = PyObject_GetAttr(v, unicodestr);
354 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000355 res = PyEval_CallObject(func, (PyObject *)NULL);
356 Py_DECREF(func);
357 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000358 else {
359 PyErr_Clear();
360 if (v->ob_type->tp_str != NULL)
361 res = (*v->ob_type->tp_str)(v);
362 else
363 res = PyObject_Repr(v);
364 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000365 }
366 if (res == NULL)
367 return NULL;
368 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000369 PyObject *str;
370 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000371 Py_DECREF(res);
372 if (str)
373 res = str;
374 else
375 return NULL;
376 }
377 return res;
378}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000379#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000380
381
Guido van Rossuma4073002002-05-31 20:03:54 +0000382/* Helper to warn about deprecated tp_compare return values. Return:
383 -2 for an exception;
384 -1 if v < w;
385 0 if v == w;
386 1 if v > w.
387 (This function cannot return 2.)
388*/
389static int
390adjust_tp_compare(int c)
391{
392 if (PyErr_Occurred()) {
393 if (c != -1 && c != -2) {
394 PyObject *t, *v, *tb;
395 PyErr_Fetch(&t, &v, &tb);
396 if (PyErr_Warn(PyExc_RuntimeWarning,
397 "tp_compare didn't return -1 or -2 "
398 "for exception") < 0) {
399 Py_XDECREF(t);
400 Py_XDECREF(v);
401 Py_XDECREF(tb);
402 }
403 else
404 PyErr_Restore(t, v, tb);
405 }
406 return -2;
407 }
408 else if (c < -1 || c > 1) {
409 if (PyErr_Warn(PyExc_RuntimeWarning,
410 "tp_compare didn't return -1, 0 or 1") < 0)
411 return -2;
412 else
413 return c < -1 ? -1 : 1;
414 }
415 else {
416 assert(c >= -1 && c <= 1);
417 return c;
418 }
419}
420
421
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000422/* Macro to get the tp_richcompare field of a type if defined */
423#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
424 ? (t)->tp_richcompare : NULL)
425
Guido van Rossume797ec12001-01-17 15:24:28 +0000426/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
427static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000428
Guido van Rossume797ec12001-01-17 15:24:28 +0000429/* Try a genuine rich comparison, returning an object. Return:
430 NULL for exception;
431 NotImplemented if this particular rich comparison is not implemented or
432 undefined;
433 some object not equal to NotImplemented if it is implemented
434 (this latter object may not be a Boolean).
435*/
436static PyObject *
437try_rich_compare(PyObject *v, PyObject *w, int op)
438{
439 richcmpfunc f;
440 PyObject *res;
441
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000442 if (v->ob_type != w->ob_type &&
443 PyType_IsSubtype(w->ob_type, v->ob_type) &&
444 (f = RICHCOMPARE(w->ob_type)) != NULL) {
445 res = (*f)(w, v, swapped_op[op]);
446 if (res != Py_NotImplemented)
447 return res;
448 Py_DECREF(res);
449 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000450 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000451 res = (*f)(v, w, op);
452 if (res != Py_NotImplemented)
453 return res;
454 Py_DECREF(res);
455 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000456 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000457 return (*f)(w, v, swapped_op[op]);
458 }
459 res = Py_NotImplemented;
460 Py_INCREF(res);
461 return res;
462}
463
464/* Try a genuine rich comparison, returning an int. Return:
465 -1 for exception (including the case where try_rich_compare() returns an
466 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000467 0 if the outcome is false;
468 1 if the outcome is true;
469 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000470*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000471static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000472try_rich_compare_bool(PyObject *v, PyObject *w, int op)
473{
474 PyObject *res;
475 int ok;
476
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000477 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000478 return 2; /* Shortcut, avoid INCREF+DECREF */
479 res = try_rich_compare(v, w, op);
480 if (res == NULL)
481 return -1;
482 if (res == Py_NotImplemented) {
483 Py_DECREF(res);
484 return 2;
485 }
486 ok = PyObject_IsTrue(res);
487 Py_DECREF(res);
488 return ok;
489}
490
491/* Try rich comparisons to determine a 3-way comparison. Return:
492 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000493 -1 if v < w;
494 0 if v == w;
495 1 if v > w;
496 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000497*/
498static int
499try_rich_to_3way_compare(PyObject *v, PyObject *w)
500{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000501 static struct { int op; int outcome; } tries[3] = {
502 /* Try this operator, and if it is true, use this outcome: */
503 {Py_EQ, 0},
504 {Py_LT, -1},
505 {Py_GT, 1},
506 };
507 int i;
508
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000509 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000510 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000511
512 for (i = 0; i < 3; i++) {
513 switch (try_rich_compare_bool(v, w, tries[i].op)) {
514 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000515 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000516 case 1:
517 return tries[i].outcome;
518 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000519 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000520
521 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000522}
523
524/* Try a 3-way comparison, returning an int. Return:
525 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000526 -1 if v < w;
527 0 if v == w;
528 1 if v > w;
529 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000530*/
531static int
532try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000533{
534 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000535 cmpfunc f;
536
537 /* Comparisons involving instances are given to instance_compare,
538 which has the same return conventions as this function. */
539
Guido van Rossumab3b0342001-09-18 20:38:53 +0000540 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000541 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000542 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000543 if (PyInstance_Check(w))
544 return (*w->ob_type->tp_compare)(v, w);
545
Guido van Rossumab3b0342001-09-18 20:38:53 +0000546 /* If both have the same (non-NULL) tp_compare, use it. */
547 if (f != NULL && f == w->ob_type->tp_compare) {
548 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000549 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000550 }
551
552 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
553 if (f == _PyObject_SlotCompare ||
554 w->ob_type->tp_compare == _PyObject_SlotCompare)
555 return _PyObject_SlotCompare(v, w);
556
Guido van Rossume797ec12001-01-17 15:24:28 +0000557 /* Try coercion; if it fails, give up */
558 c = PyNumber_CoerceEx(&v, &w);
559 if (c < 0)
560 return -2;
561 if (c > 0)
562 return 2;
563
564 /* Try v's comparison, if defined */
565 if ((f = v->ob_type->tp_compare) != NULL) {
566 c = (*f)(v, w);
567 Py_DECREF(v);
568 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000569 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000570 }
571
572 /* Try w's comparison, if defined */
573 if ((f = w->ob_type->tp_compare) != NULL) {
574 c = (*f)(w, v); /* swapped! */
575 Py_DECREF(v);
576 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000577 c = adjust_tp_compare(c);
578 if (c >= -1)
579 return -c; /* Swapped! */
580 else
581 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000582 }
583
584 /* No comparison defined */
585 Py_DECREF(v);
586 Py_DECREF(w);
587 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000588}
589
Guido van Rossume797ec12001-01-17 15:24:28 +0000590/* Final fallback 3-way comparison, returning an int. Return:
591 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000592 -1 if v < w;
593 0 if v == w;
594 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000595*/
596static int
597default_3way_compare(PyObject *v, PyObject *w)
598{
599 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000600 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000601
602 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000603 /* When comparing these pointers, they must be cast to
604 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
605 * uintptr_t). ANSI specifies that pointer compares other
606 * than == and != to non-related structures are undefined.
607 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000608 Py_uintptr_t vv = (Py_uintptr_t)v;
609 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000610 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
611 }
612
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000613#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000614 /* Special case for Unicode */
615 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
616 c = PyUnicode_Compare(v, w);
617 if (!PyErr_Occurred())
618 return c;
619 /* TypeErrors are ignored: if Unicode coercion fails due
620 to one of the arguments not having the right type, we
621 continue as defined by the coercion protocol (see
622 above). Luckily, decoding errors are reported as
623 ValueErrors and are not masked by this technique. */
624 if (!PyErr_ExceptionMatches(PyExc_TypeError))
625 return -2;
626 PyErr_Clear();
627 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000628#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000629
Guido van Rossum0871e932001-01-22 19:28:09 +0000630 /* None is smaller than anything */
631 if (v == Py_None)
632 return -1;
633 if (w == Py_None)
634 return 1;
635
Guido van Rossume797ec12001-01-17 15:24:28 +0000636 /* different type: compare type names */
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000637 if (v->ob_type->tp_as_number)
638 vname = "";
639 else
640 vname = v->ob_type->tp_name;
641 if (w->ob_type->tp_as_number)
642 wname = "";
643 else
644 wname = w->ob_type->tp_name;
645 c = strcmp(vname, wname);
646 if (c < 0)
647 return -1;
648 if (c > 0)
649 return 1;
650 /* Same type name, or (more likely) incomparable numeric types */
651 return ((Py_uintptr_t)(v->ob_type) < (
652 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000653}
654
655#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
656
Tim Peters6d60b2e2001-05-07 20:53:51 +0000657/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000658 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000659 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000660 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000661 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000662 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000663 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000664*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000665static int
Fred Drake100814d2000-07-09 15:48:49 +0000666do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000667{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000668 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000669 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000670
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000671 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000672 && (f = v->ob_type->tp_compare) != NULL) {
673 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000674 if (PyInstance_Check(v)) {
675 /* Instance tp_compare has a different signature.
676 But if it returns undefined we fall through. */
677 if (c != 2)
678 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000679 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000680 }
681 else
682 return adjust_tp_compare(c);
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000683 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000684 /* We only get here if one of the following is true:
685 a) v and w have different types
686 b) v and w have the same type, which doesn't have tp_compare
687 c) v and w are instances, and either __cmp__ is not defined or
688 __cmp__ returns NotImplemented
689 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000690 c = try_rich_to_3way_compare(v, w);
691 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000692 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000693 c = try_3way_compare(v, w);
694 if (c < 2)
695 return c;
696 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000697}
698
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000699/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000700 some types) and decremented on exit. If the count exceeds the
701 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000702
703 This is a tunable parameter that should only affect the performance
704 of comparisons, nothing else. Setting it high makes comparing deeply
705 nested non-cyclical data structures faster, but makes comparing cyclical
706 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000707*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000708#define NESTING_LIMIT 20
709
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000710static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000711
712static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000713get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000714{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000715 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000716 PyObject *tstate_dict, *inprogress;
717
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000718 if (key == NULL) {
719 key = PyString_InternFromString("cmp_state");
720 if (key == NULL)
721 return NULL;
722 }
723
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000724 tstate_dict = PyThreadState_GetDict();
725 if (tstate_dict == NULL) {
726 PyErr_BadInternalCall();
727 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000728 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000729
Tim Peters803526b2002-07-07 05:13:56 +0000730 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000731 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000732 inprogress = PyDict_New();
733 if (inprogress == NULL)
734 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000735 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000736 Py_DECREF(inprogress);
737 return NULL;
738 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000739 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000740 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000741
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000742 return inprogress;
743}
744
745static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000746check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000747{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000748 PyObject *inprogress;
749 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000750 Py_uintptr_t iv = (Py_uintptr_t)v;
751 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000752 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000753
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000754 inprogress = get_inprogress_dict();
755 if (inprogress == NULL)
756 return NULL;
757
758 token = PyTuple_New(3);
759 if (token == NULL)
760 return NULL;
761
762 if (iv <= iw) {
763 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
764 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
765 if (op >= 0)
766 op = swapped_op[op];
767 } else {
768 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
769 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
770 }
771 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
772 if (x == NULL || y == NULL || z == NULL) {
773 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000774 return NULL;
775 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000776
777 if (PyDict_GetItem(inprogress, token) != NULL) {
778 Py_DECREF(token);
779 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000780 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000781
782 if (PyDict_SetItem(inprogress, token, token) < 0) {
783 Py_DECREF(token);
784 return NULL;
785 }
786
787 return token;
788}
789
790static void
791delete_token(PyObject *token)
792{
793 PyObject *inprogress;
794
795 if (token == NULL || token == Py_None)
796 return;
797 inprogress = get_inprogress_dict();
798 if (inprogress == NULL)
799 PyErr_Clear();
800 else
801 PyDict_DelItem(inprogress, token);
802 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000803}
804
Tim Petersc99213f2001-11-04 05:57:16 +0000805/* Compare v to w. Return
806 -1 if v < w or exception (PyErr_Occurred() true in latter case).
807 0 if v == w.
808 1 if v > w.
809 XXX The docs (C API manual) say the return value is undefined in case
810 XXX of error.
811*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812int
Fred Drake100814d2000-07-09 15:48:49 +0000813PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000814{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000815 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000816 int result;
817
Jack Jansend49cbe12000-08-22 21:52:51 +0000818#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000819 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000820 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000821 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000822 }
823#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000824 if (v == NULL || w == NULL) {
825 PyErr_BadInternalCall();
826 return -1;
827 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000828 if (v == w)
829 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000830 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000831 compare_nesting++;
832 if (compare_nesting > NESTING_LIMIT &&
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000833 (vtp->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000834 || (vtp->tp_as_sequence
835 && !PyString_Check(v)
836 && !PyTuple_Check(v)))) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000837 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000838 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000839
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000840 if (token == NULL) {
841 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000842 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000843 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000844 /* already comparing these objects. assume
845 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000846 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000847 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000848 else {
849 result = do_cmp(v, w);
850 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000851 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000852 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000853 else {
854 result = do_cmp(v, w);
855 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000856 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000857 return result < 0 ? -1 : result;
858}
859
Tim Petersc99213f2001-11-04 05:57:16 +0000860/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000861static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000862convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000863{
Guido van Rossume797ec12001-01-17 15:24:28 +0000864 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000865 switch (op) {
866 case Py_LT: c = c < 0; break;
867 case Py_LE: c = c <= 0; break;
868 case Py_EQ: c = c == 0; break;
869 case Py_NE: c = c != 0; break;
870 case Py_GT: c = c > 0; break;
871 case Py_GE: c = c >= 0; break;
872 }
873 result = c ? Py_True : Py_False;
874 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000875 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000876}
Tim Peters803526b2002-07-07 05:13:56 +0000877
Tim Petersc99213f2001-11-04 05:57:16 +0000878/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
879 Return
880 NULL if error
881 Py_True if v op w
882 Py_False if not (v op w)
883*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000884static PyObject *
885try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
886{
887 int c;
888
889 c = try_3way_compare(v, w);
890 if (c >= 2)
891 c = default_3way_compare(v, w);
892 if (c <= -2)
893 return NULL;
894 return convert_3way_to_object(op, c);
895}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000896
Tim Petersc99213f2001-11-04 05:57:16 +0000897/* Do rich comparison on v and w. Return
898 NULL if error
899 Else a new reference to an object other than Py_NotImplemented, usually(?):
900 Py_True if v op w
901 Py_False if not (v op w)
902*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000903static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000904do_richcmp(PyObject *v, PyObject *w, int op)
905{
906 PyObject *res;
907
908 res = try_rich_compare(v, w, op);
909 if (res != Py_NotImplemented)
910 return res;
911 Py_DECREF(res);
912
913 return try_3way_to_rich_compare(v, w, op);
914}
915
Tim Petersc99213f2001-11-04 05:57:16 +0000916/* Return:
917 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000918 some object not equal to NotImplemented if it is implemented
919 (this latter object may not be a Boolean).
920*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000921PyObject *
922PyObject_RichCompare(PyObject *v, PyObject *w, int op)
923{
924 PyObject *res;
925
926 assert(Py_LT <= op && op <= Py_GE);
927
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000928 compare_nesting++;
929 if (compare_nesting > NESTING_LIMIT &&
930 (v->ob_type->tp_as_mapping
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000931 || (v->ob_type->tp_as_sequence
932 && !PyString_Check(v)
933 && !PyTuple_Check(v)))) {
Tim Peters67754e92001-11-04 07:29:31 +0000934
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000935 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000936 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000937 if (token == NULL) {
938 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000939 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000940 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000941 else if (token == Py_None) {
942 /* already comparing these objects with this operator.
943 assume they're equal until shown otherwise */
944 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000945 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000946 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000947 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000948 else {
949 PyErr_SetString(PyExc_ValueError,
950 "can't order recursive values");
951 res = NULL;
952 }
953 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000954 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000955 else {
956 res = do_richcmp(v, w, op);
957 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000958 }
Tim Peters67754e92001-11-04 07:29:31 +0000959 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000960 }
Tim Peters67754e92001-11-04 07:29:31 +0000961
962 /* No nesting extremism.
963 If the types are equal, and not old-style instances, try to
964 get out cheap (don't bother with coercions etc.). */
965 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
966 cmpfunc fcmp;
967 richcmpfunc frich = RICHCOMPARE(v->ob_type);
968 /* If the type has richcmp, try it first. try_rich_compare
969 tries it two-sided, which is not needed since we've a
970 single type only. */
971 if (frich != NULL) {
972 res = (*frich)(v, w, op);
973 if (res != Py_NotImplemented)
974 goto Done;
975 Py_DECREF(res);
976 }
977 /* No richcmp, or this particular richmp not implemented.
978 Try 3-way cmp. */
979 fcmp = v->ob_type->tp_compare;
980 if (fcmp != NULL) {
981 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000982 c = adjust_tp_compare(c);
983 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000984 res = NULL;
985 goto Done;
986 }
987 res = convert_3way_to_object(op, c);
988 goto Done;
989 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000990 }
Tim Peters67754e92001-11-04 07:29:31 +0000991
992 /* Fast path not taken, or couldn't deliver a useful result. */
993 res = do_richcmp(v, w, op);
994Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000995 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000996 return res;
997}
998
Tim Petersde9725f2001-05-05 10:06:17 +0000999/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +00001000int
1001PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
1002{
1003 PyObject *res = PyObject_RichCompare(v, w, op);
1004 int ok;
1005
1006 if (res == NULL)
1007 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +00001008 if (PyBool_Check(res))
1009 ok = (res == Py_True);
1010 else
1011 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +00001012 Py_DECREF(res);
1013 return ok;
1014}
Fred Drake13634cf2000-06-29 19:17:04 +00001015
1016/* Set of hash utility functions to help maintaining the invariant that
1017 iff a==b then hash(a)==hash(b)
1018
1019 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1020*/
1021
1022long
Fred Drake100814d2000-07-09 15:48:49 +00001023_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001024{
Tim Peters39dce292000-08-15 03:34:48 +00001025 double intpart, fractpart;
1026 int expo;
1027 long hipart;
1028 long x; /* the final hash value */
1029 /* This is designed so that Python numbers of different types
1030 * that compare equal hash to the same value; otherwise comparisons
1031 * of mapping keys will turn out weird.
1032 */
1033
1034#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1035{
1036 extended e;
1037 fractpart = modf(v, &e);
1038 intpart = e;
1039}
1040#else
1041 fractpart = modf(v, &intpart);
1042#endif
1043 if (fractpart == 0.0) {
1044 /* This must return the same hash as an equal int or long. */
1045 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1046 /* Convert to long and use its hash. */
1047 PyObject *plong; /* converted to Python long */
1048 if (Py_IS_INFINITY(intpart))
1049 /* can't convert to long int -- arbitrary */
1050 v = v < 0 ? -271828.0 : 314159.0;
1051 plong = PyLong_FromDouble(v);
1052 if (plong == NULL)
1053 return -1;
1054 x = PyObject_Hash(plong);
1055 Py_DECREF(plong);
1056 return x;
1057 }
1058 /* Fits in a C long == a Python int, so is its own hash. */
1059 x = (long)intpart;
1060 if (x == -1)
1061 x = -2;
1062 return x;
1063 }
1064 /* The fractional part is non-zero, so we don't have to worry about
1065 * making this match the hash of some other type.
1066 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001067 * Since the VAX D double format has 56 mantissa bits, which is the
1068 * most of any double format in use, each of these parts may have as
1069 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001070 * So, assuming sizeof(long) >= 4, each part can be broken into two
1071 * longs; frexp and multiplication are used to do that.
1072 * Also, since the Cray double format has 15 exponent bits, which is
1073 * the most of any double format in use, shifting the exponent field
1074 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001075 */
Tim Peters39dce292000-08-15 03:34:48 +00001076 v = frexp(v, &expo);
1077 v *= 2147483648.0; /* 2**31 */
1078 hipart = (long)v; /* take the top 32 bits */
1079 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1080 x = hipart + (long)v + (expo << 15);
1081 if (x == -1)
1082 x = -2;
1083 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001084}
1085
1086long
Fred Drake100814d2000-07-09 15:48:49 +00001087_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001088{
1089#if SIZEOF_LONG >= SIZEOF_VOID_P
1090 return (long)p;
1091#else
1092 /* convert to a Python long and hash that */
1093 PyObject* longobj;
1094 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001095
Fred Drake13634cf2000-06-29 19:17:04 +00001096 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1097 x = -1;
1098 goto finally;
1099 }
1100 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001101
Fred Drake13634cf2000-06-29 19:17:04 +00001102finally:
1103 Py_XDECREF(longobj);
1104 return x;
1105#endif
1106}
1107
1108
Guido van Rossum9bfef441993-03-29 10:43:31 +00001109long
Fred Drake100814d2000-07-09 15:48:49 +00001110PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001111{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001112 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001113 if (tp->tp_hash != NULL)
1114 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001115 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001116 return _Py_HashPointer(v); /* Use address as hash value */
1117 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001118 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001119 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001120 return -1;
1121}
1122
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001123PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001124PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001125{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001126 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001127
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001129 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001130 w = PyString_InternFromString(name);
1131 if (w == NULL)
1132 return NULL;
1133 res = PyObject_GetAttr(v, w);
1134 Py_XDECREF(w);
1135 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001136}
1137
1138int
Fred Drake100814d2000-07-09 15:48:49 +00001139PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001140{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001141 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001142 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001143 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001144 return 1;
1145 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001146 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001147 return 0;
1148}
1149
1150int
Fred Drake100814d2000-07-09 15:48:49 +00001151PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001152{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 PyObject *s;
1154 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001155
Tim Peters6d6c1a32001-08-02 04:15:00 +00001156 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001157 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001158 s = PyString_InternFromString(name);
1159 if (s == NULL)
1160 return -1;
1161 res = PyObject_SetAttr(v, s, w);
1162 Py_XDECREF(s);
1163 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001164}
1165
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001166PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001167PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001168{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 PyTypeObject *tp = v->ob_type;
1170
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001171 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001172#ifdef Py_USING_UNICODE
1173 /* The Unicode to string conversion is done here because the
1174 existing tp_getattro slots expect a string object as name
1175 and we wouldn't want to break those. */
1176 if (PyUnicode_Check(name)) {
1177 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1178 if (name == NULL)
1179 return NULL;
1180 }
1181 else
1182#endif
1183 {
1184 PyErr_SetString(PyExc_TypeError,
1185 "attribute name must be string");
1186 return NULL;
1187 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001188 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 if (tp->tp_getattro != NULL)
1190 return (*tp->tp_getattro)(v, name);
1191 if (tp->tp_getattr != NULL)
1192 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1193 PyErr_Format(PyExc_AttributeError,
1194 "'%.50s' object has no attribute '%.400s'",
1195 tp->tp_name, PyString_AS_STRING(name));
1196 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001197}
1198
1199int
Fred Drake100814d2000-07-09 15:48:49 +00001200PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001201{
1202 PyObject *res = PyObject_GetAttr(v, name);
1203 if (res != NULL) {
1204 Py_DECREF(res);
1205 return 1;
1206 }
1207 PyErr_Clear();
1208 return 0;
1209}
1210
1211int
Fred Drake100814d2000-07-09 15:48:49 +00001212PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001213{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001215 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001216
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001217 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001218#ifdef Py_USING_UNICODE
1219 /* The Unicode to string conversion is done here because the
1220 existing tp_setattro slots expect a string object as name
1221 and we wouldn't want to break those. */
1222 if (PyUnicode_Check(name)) {
1223 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1224 if (name == NULL)
1225 return -1;
1226 }
Tim Peters803526b2002-07-07 05:13:56 +00001227 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001228#endif
1229 {
1230 PyErr_SetString(PyExc_TypeError,
1231 "attribute name must be string");
1232 return -1;
1233 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001234 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001235 else
1236 Py_INCREF(name);
1237
1238 PyString_InternInPlace(&name);
1239 if (tp->tp_setattro != NULL) {
1240 err = (*tp->tp_setattro)(v, name, value);
1241 Py_DECREF(name);
1242 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001243 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244 if (tp->tp_setattr != NULL) {
1245 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1246 Py_DECREF(name);
1247 return err;
1248 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001249 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1251 PyErr_Format(PyExc_TypeError,
1252 "'%.100s' object has no attributes "
1253 "(%s .%.100s)",
1254 tp->tp_name,
1255 value==NULL ? "del" : "assign to",
1256 PyString_AS_STRING(name));
1257 else
1258 PyErr_Format(PyExc_TypeError,
1259 "'%.100s' object has only read-only attributes "
1260 "(%s .%.100s)",
1261 tp->tp_name,
1262 value==NULL ? "del" : "assign to",
1263 PyString_AS_STRING(name));
1264 return -1;
1265}
1266
1267/* Helper to get a pointer to an object's __dict__ slot, if any */
1268
1269PyObject **
1270_PyObject_GetDictPtr(PyObject *obj)
1271{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272 long dictoffset;
1273 PyTypeObject *tp = obj->ob_type;
1274
1275 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1276 return NULL;
1277 dictoffset = tp->tp_dictoffset;
1278 if (dictoffset == 0)
1279 return NULL;
1280 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001281 int tsize;
1282 size_t size;
1283
1284 tsize = ((PyVarObject *)obj)->ob_size;
1285 if (tsize < 0)
1286 tsize = -tsize;
1287 size = _PyObject_VAR_SIZE(tp, tsize);
1288
Tim Peters6d483d32001-10-06 21:27:34 +00001289 dictoffset += (long)size;
1290 assert(dictoffset > 0);
1291 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 }
1293 return (PyObject **) ((char *)obj + dictoffset);
1294}
1295
1296/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1297
1298PyObject *
1299PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1300{
1301 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001302 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001303 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001305 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306 PyObject **dictptr;
1307
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001308 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001309#ifdef Py_USING_UNICODE
1310 /* The Unicode to string conversion is done here because the
1311 existing tp_setattro slots expect a string object as name
1312 and we wouldn't want to break those. */
1313 if (PyUnicode_Check(name)) {
1314 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1315 if (name == NULL)
1316 return NULL;
1317 }
Tim Peters803526b2002-07-07 05:13:56 +00001318 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001319#endif
1320 {
1321 PyErr_SetString(PyExc_TypeError,
1322 "attribute name must be string");
1323 return NULL;
1324 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001325 }
1326 else
1327 Py_INCREF(name);
1328
Tim Peters6d6c1a32001-08-02 04:15:00 +00001329 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001330 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001331 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332 }
1333
Guido van Rossum056fbf42002-08-19 19:22:50 +00001334 /* Inline _PyType_Lookup */
1335 {
1336 int i, n;
1337 PyObject *mro, *base, *dict;
1338
1339 /* Look in tp_dict of types in MRO */
1340 mro = tp->tp_mro;
1341 assert(mro != NULL);
1342 assert(PyTuple_Check(mro));
1343 n = PyTuple_GET_SIZE(mro);
1344 for (i = 0; i < n; i++) {
1345 base = PyTuple_GET_ITEM(mro, i);
1346 if (PyClass_Check(base))
1347 dict = ((PyClassObject *)base)->cl_dict;
1348 else {
1349 assert(PyType_Check(base));
1350 dict = ((PyTypeObject *)base)->tp_dict;
1351 }
1352 assert(dict && PyDict_Check(dict));
1353 descr = PyDict_GetItem(dict, name);
1354 if (descr != NULL)
1355 break;
1356 }
1357 }
1358
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 f = NULL;
1360 if (descr != NULL) {
1361 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001362 if (f != NULL && PyDescr_IsData(descr)) {
1363 res = f(descr, obj, (PyObject *)obj->ob_type);
1364 goto done;
1365 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 }
1367
Guido van Rossumc66ff442002-08-19 16:50:48 +00001368 /* Inline _PyObject_GetDictPtr */
1369 dictoffset = tp->tp_dictoffset;
1370 if (dictoffset != 0) {
1371 PyObject *dict;
1372 if (dictoffset < 0) {
1373 int tsize;
1374 size_t size;
1375
1376 tsize = ((PyVarObject *)obj)->ob_size;
1377 if (tsize < 0)
1378 tsize = -tsize;
1379 size = _PyObject_VAR_SIZE(tp, tsize);
1380
1381 dictoffset += (long)size;
1382 assert(dictoffset > 0);
1383 assert(dictoffset % SIZEOF_VOID_P == 0);
1384 }
1385 dictptr = (PyObject **) ((char *)obj + dictoffset);
1386 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001387 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001388 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001389 if (res != NULL) {
1390 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001391 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392 }
1393 }
1394 }
1395
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001396 if (f != NULL) {
1397 res = f(descr, obj, (PyObject *)obj->ob_type);
1398 goto done;
1399 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001400
1401 if (descr != NULL) {
1402 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001403 res = descr;
1404 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001405 }
1406
1407 PyErr_Format(PyExc_AttributeError,
1408 "'%.50s' object has no attribute '%.400s'",
1409 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001410 done:
1411 Py_DECREF(name);
1412 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001413}
1414
1415int
1416PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1417{
1418 PyTypeObject *tp = obj->ob_type;
1419 PyObject *descr;
1420 descrsetfunc f;
1421 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001422 int res = -1;
1423
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001424 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001425#ifdef Py_USING_UNICODE
1426 /* The Unicode to string conversion is done here because the
1427 existing tp_setattro slots expect a string object as name
1428 and we wouldn't want to break those. */
1429 if (PyUnicode_Check(name)) {
1430 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1431 if (name == NULL)
1432 return -1;
1433 }
Tim Peters803526b2002-07-07 05:13:56 +00001434 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001435#endif
1436 {
1437 PyErr_SetString(PyExc_TypeError,
1438 "attribute name must be string");
1439 return -1;
1440 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001441 }
1442 else
1443 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001444
1445 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001446 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001447 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448 }
1449
1450 descr = _PyType_Lookup(tp, name);
1451 f = NULL;
1452 if (descr != NULL) {
1453 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001454 if (f != NULL && PyDescr_IsData(descr)) {
1455 res = f(descr, obj, value);
1456 goto done;
1457 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001458 }
1459
1460 dictptr = _PyObject_GetDictPtr(obj);
1461 if (dictptr != NULL) {
1462 PyObject *dict = *dictptr;
1463 if (dict == NULL && value != NULL) {
1464 dict = PyDict_New();
1465 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001466 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001467 *dictptr = dict;
1468 }
1469 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001470 if (value == NULL)
1471 res = PyDict_DelItem(dict, name);
1472 else
1473 res = PyDict_SetItem(dict, name, value);
1474 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1475 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001476 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001477 }
1478 }
1479
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001480 if (f != NULL) {
1481 res = f(descr, obj, value);
1482 goto done;
1483 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001484
1485 if (descr == NULL) {
1486 PyErr_Format(PyExc_AttributeError,
1487 "'%.50s' object has no attribute '%.400s'",
1488 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001489 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001490 }
1491
1492 PyErr_Format(PyExc_AttributeError,
1493 "'%.50s' object attribute '%.400s' is read-only",
1494 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001495 done:
1496 Py_DECREF(name);
1497 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001498}
1499
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001500/* Test a value used as condition, e.g., in a for or if statement.
1501 Return -1 if an error occurred */
1502
1503int
Fred Drake100814d2000-07-09 15:48:49 +00001504PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001505{
1506 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001507 if (v == Py_True)
1508 return 1;
1509 if (v == Py_False)
1510 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001511 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001512 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001513 else if (v->ob_type->tp_as_number != NULL &&
1514 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001515 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001516 else if (v->ob_type->tp_as_mapping != NULL &&
1517 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001518 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001519 else if (v->ob_type->tp_as_sequence != NULL &&
1520 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001521 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1522 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001523 return 1;
1524 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001525}
1526
Tim Peters803526b2002-07-07 05:13:56 +00001527/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001528 Return -1 if an error occurred */
1529
1530int
Fred Drake100814d2000-07-09 15:48:49 +00001531PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001532{
1533 int res;
1534 res = PyObject_IsTrue(v);
1535 if (res < 0)
1536 return res;
1537 return res == 0;
1538}
1539
Guido van Rossum5524a591995-01-10 15:26:20 +00001540/* Coerce two numeric types to the "larger" one.
1541 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001542 Return value:
1543 -1 if an error occurred;
1544 0 if the coercion succeeded (and then the reference counts are increased);
1545 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001546*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001547int
Fred Drake100814d2000-07-09 15:48:49 +00001548PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001549{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001550 register PyObject *v = *pv;
1551 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001552 int res;
1553
Guido van Rossum517c7d42002-04-26 02:49:14 +00001554 /* Shortcut only for old-style types */
1555 if (v->ob_type == w->ob_type &&
1556 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1557 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001558 Py_INCREF(v);
1559 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001560 return 0;
1561 }
1562 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1563 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1564 if (res <= 0)
1565 return res;
1566 }
1567 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1568 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1569 if (res <= 0)
1570 return res;
1571 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001572 return 1;
1573}
1574
Guido van Rossume797ec12001-01-17 15:24:28 +00001575/* Coerce two numeric types to the "larger" one.
1576 Increment the reference count on each argument.
1577 Return -1 and raise an exception if no coercion is possible
1578 (and then no reference count is incremented).
1579*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001580int
Fred Drake100814d2000-07-09 15:48:49 +00001581PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001582{
1583 int err = PyNumber_CoerceEx(pv, pw);
1584 if (err <= 0)
1585 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001586 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001587 return -1;
1588}
1589
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001590
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001591/* Test whether an object can be called */
1592
1593int
Fred Drake100814d2000-07-09 15:48:49 +00001594PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001595{
1596 if (x == NULL)
1597 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001598 if (PyInstance_Check(x)) {
1599 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001600 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001601 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001602 return 0;
1603 }
1604 /* Could test recursively but don't, for fear of endless
1605 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001606 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001607 return 1;
1608 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001609 else {
1610 return x->ob_type->tp_call != NULL;
1611 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001612}
1613
Tim Peters7eea37e2001-09-04 22:08:56 +00001614/* Helper for PyObject_Dir.
1615 Merge the __dict__ of aclass into dict, and recursively also all
1616 the __dict__s of aclass's base classes. The order of merging isn't
1617 defined, as it's expected that only the final set of dict keys is
1618 interesting.
1619 Return 0 on success, -1 on error.
1620*/
1621
1622static int
1623merge_class_dict(PyObject* dict, PyObject* aclass)
1624{
1625 PyObject *classdict;
1626 PyObject *bases;
1627
1628 assert(PyDict_Check(dict));
1629 assert(aclass);
1630
1631 /* Merge in the type's dict (if any). */
1632 classdict = PyObject_GetAttrString(aclass, "__dict__");
1633 if (classdict == NULL)
1634 PyErr_Clear();
1635 else {
1636 int status = PyDict_Update(dict, classdict);
1637 Py_DECREF(classdict);
1638 if (status < 0)
1639 return -1;
1640 }
1641
1642 /* Recursively merge in the base types' (if any) dicts. */
1643 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001644 if (bases == NULL)
1645 PyErr_Clear();
1646 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001647 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001648 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001649 n = PySequence_Size(bases); /* This better be right */
1650 if (n < 0)
1651 PyErr_Clear();
1652 else {
1653 for (i = 0; i < n; i++) {
1654 PyObject *base = PySequence_GetItem(bases, i);
1655 if (base == NULL) {
1656 Py_DECREF(bases);
1657 return -1;
1658 }
1659 if (merge_class_dict(dict, base) < 0) {
1660 Py_DECREF(bases);
1661 return -1;
1662 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001663 }
1664 }
1665 Py_DECREF(bases);
1666 }
1667 return 0;
1668}
1669
Tim Peters305b5852001-09-17 02:38:46 +00001670/* Helper for PyObject_Dir.
1671 If obj has an attr named attrname that's a list, merge its string
1672 elements into keys of dict.
1673 Return 0 on success, -1 on error. Errors due to not finding the attr,
1674 or the attr not being a list, are suppressed.
1675*/
1676
1677static int
1678merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1679{
1680 PyObject *list;
1681 int result = 0;
1682
1683 assert(PyDict_Check(dict));
1684 assert(obj);
1685 assert(attrname);
1686
1687 list = PyObject_GetAttrString(obj, attrname);
1688 if (list == NULL)
1689 PyErr_Clear();
1690
1691 else if (PyList_Check(list)) {
1692 int i;
1693 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1694 PyObject *item = PyList_GET_ITEM(list, i);
1695 if (PyString_Check(item)) {
1696 result = PyDict_SetItem(dict, item, Py_None);
1697 if (result < 0)
1698 break;
1699 }
1700 }
1701 }
1702
1703 Py_XDECREF(list);
1704 return result;
1705}
1706
Tim Peters7eea37e2001-09-04 22:08:56 +00001707/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1708 docstring, which should be kept in synch with this implementation. */
1709
1710PyObject *
1711PyObject_Dir(PyObject *arg)
1712{
1713 /* Set exactly one of these non-NULL before the end. */
1714 PyObject *result = NULL; /* result list */
1715 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1716
1717 /* If NULL arg, return the locals. */
1718 if (arg == NULL) {
1719 PyObject *locals = PyEval_GetLocals();
1720 if (locals == NULL)
1721 goto error;
1722 result = PyDict_Keys(locals);
1723 if (result == NULL)
1724 goto error;
1725 }
1726
1727 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001728 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001729 masterdict = PyObject_GetAttrString(arg, "__dict__");
1730 if (masterdict == NULL)
1731 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001732 if (!PyDict_Check(masterdict)) {
1733 PyErr_SetString(PyExc_TypeError,
1734 "module.__dict__ is not a dictionary");
1735 goto error;
1736 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001737 }
1738
1739 /* Elif some form of type or class, grab its dict and its bases.
1740 We deliberately don't suck up its __class__, as methods belonging
1741 to the metaclass would probably be more confusing than helpful. */
1742 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1743 masterdict = PyDict_New();
1744 if (masterdict == NULL)
1745 goto error;
1746 if (merge_class_dict(masterdict, arg) < 0)
1747 goto error;
1748 }
1749
1750 /* Else look at its dict, and the attrs reachable from its class. */
1751 else {
1752 PyObject *itsclass;
1753 /* Create a dict to start with. CAUTION: Not everything
1754 responding to __dict__ returns a dict! */
1755 masterdict = PyObject_GetAttrString(arg, "__dict__");
1756 if (masterdict == NULL) {
1757 PyErr_Clear();
1758 masterdict = PyDict_New();
1759 }
1760 else if (!PyDict_Check(masterdict)) {
1761 Py_DECREF(masterdict);
1762 masterdict = PyDict_New();
1763 }
1764 else {
1765 /* The object may have returned a reference to its
1766 dict, so copy it to avoid mutating it. */
1767 PyObject *temp = PyDict_Copy(masterdict);
1768 Py_DECREF(masterdict);
1769 masterdict = temp;
1770 }
1771 if (masterdict == NULL)
1772 goto error;
1773
Tim Peters305b5852001-09-17 02:38:46 +00001774 /* Merge in __members__ and __methods__ (if any).
1775 XXX Would like this to go away someday; for now, it's
1776 XXX needed to get at im_self etc of method objects. */
1777 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1778 goto error;
1779 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1780 goto error;
1781
Tim Peters7eea37e2001-09-04 22:08:56 +00001782 /* Merge in attrs reachable from its class.
1783 CAUTION: Not all objects have a __class__ attr. */
1784 itsclass = PyObject_GetAttrString(arg, "__class__");
1785 if (itsclass == NULL)
1786 PyErr_Clear();
1787 else {
1788 int status = merge_class_dict(masterdict, itsclass);
1789 Py_DECREF(itsclass);
1790 if (status < 0)
1791 goto error;
1792 }
1793 }
1794
1795 assert((result == NULL) ^ (masterdict == NULL));
1796 if (masterdict != NULL) {
1797 /* The result comes from its keys. */
1798 assert(result == NULL);
1799 result = PyDict_Keys(masterdict);
1800 if (result == NULL)
1801 goto error;
1802 }
1803
1804 assert(result);
1805 if (PyList_Sort(result) != 0)
1806 goto error;
1807 else
1808 goto normal_return;
1809
1810 error:
1811 Py_XDECREF(result);
1812 result = NULL;
1813 /* fall through */
1814 normal_return:
1815 Py_XDECREF(masterdict);
1816 return result;
1817}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001818
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819/*
1820NoObject is usable as a non-NULL undefined value, used by the macro None.
1821There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001822so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001823(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001824*/
1825
Guido van Rossum0c182a11992-03-27 17:26:13 +00001826/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001827static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001828none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001829{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001830 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001831}
1832
Barry Warsaw9bf16442001-01-23 16:24:35 +00001833/* ARGUSED */
1834static void
Tim Peters803526b2002-07-07 05:13:56 +00001835none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001836{
1837 /* This should never get called, but we also don't want to SEGV if
1838 * we accidently decref None out of existance.
1839 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001840 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001841}
1842
1843
Guido van Rossumba21a492001-08-16 08:17:26 +00001844static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001845 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001847 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001848 0,
1849 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001850 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001851 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001852 0, /*tp_getattr*/
1853 0, /*tp_setattr*/
1854 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001855 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001856 0, /*tp_as_number*/
1857 0, /*tp_as_sequence*/
1858 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001859 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001860};
1861
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001862PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001863 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001864};
1865
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001866/* NotImplemented is an object that can be used to signal that an
1867 operation is not implemented for the given type combination. */
1868
1869static PyObject *
1870NotImplemented_repr(PyObject *op)
1871{
1872 return PyString_FromString("NotImplemented");
1873}
1874
1875static PyTypeObject PyNotImplemented_Type = {
1876 PyObject_HEAD_INIT(&PyType_Type)
1877 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001878 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001879 0,
1880 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001881 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001882 0, /*tp_print*/
1883 0, /*tp_getattr*/
1884 0, /*tp_setattr*/
1885 0, /*tp_compare*/
1886 (reprfunc)NotImplemented_repr, /*tp_repr*/
1887 0, /*tp_as_number*/
1888 0, /*tp_as_sequence*/
1889 0, /*tp_as_mapping*/
1890 0, /*tp_hash */
1891};
1892
1893PyObject _Py_NotImplementedStruct = {
1894 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1895};
1896
Guido van Rossumba21a492001-08-16 08:17:26 +00001897void
1898_Py_ReadyTypes(void)
1899{
1900 if (PyType_Ready(&PyType_Type) < 0)
1901 Py_FatalError("Can't initialize 'type'");
1902
Guido van Rossum77f6a652002-04-03 22:41:51 +00001903 if (PyType_Ready(&PyBool_Type) < 0)
1904 Py_FatalError("Can't initialize 'bool'");
1905
Guido van Rossumcacfc072002-05-24 19:01:59 +00001906 if (PyType_Ready(&PyString_Type) < 0)
1907 Py_FatalError("Can't initialize 'str'");
1908
Guido van Rossumba21a492001-08-16 08:17:26 +00001909 if (PyType_Ready(&PyList_Type) < 0)
1910 Py_FatalError("Can't initialize 'list'");
1911
1912 if (PyType_Ready(&PyNone_Type) < 0)
1913 Py_FatalError("Can't initialize type(None)");
1914
1915 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1916 Py_FatalError("Can't initialize type(NotImplemented)");
1917}
1918
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001919
Guido van Rossum84a90321996-05-22 16:34:47 +00001920#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001921
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001922static PyObject refchain = {&refchain, &refchain};
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001923
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001924void
Fred Drake100814d2000-07-09 15:48:49 +00001925_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001926{
Tim Peters34592512002-07-11 06:23:50 +00001927 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001928 op->ob_refcnt = 1;
1929 op->_ob_next = refchain._ob_next;
1930 op->_ob_prev = &refchain;
1931 refchain._ob_next->_ob_prev = op;
1932 refchain._ob_next = op;
Tim Peters34592512002-07-11 06:23:50 +00001933 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001934}
1935
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001936void
Fred Drake100814d2000-07-09 15:48:49 +00001937_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001938{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001939#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001940 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001941#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001942 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001943 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001944 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001945 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001946 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001947#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001948 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1949 if (p == op)
1950 break;
1951 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001952 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001953 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001954#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001955 op->_ob_next->_ob_prev = op->_ob_prev;
1956 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001957 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001958 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001959}
1960
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001961void
Fred Drake100814d2000-07-09 15:48:49 +00001962_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001963{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001964 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001965 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001966 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001967}
1968
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001969void
Fred Drake100814d2000-07-09 15:48:49 +00001970_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001971{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001972 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001973 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001974 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1975 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976 if (PyObject_Print(op, fp, 0) != 0)
1977 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001978 putc('\n', fp);
1979 }
1980}
1981
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001982PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001983_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001984{
1985 int i, n;
1986 PyObject *t = NULL;
1987 PyObject *res, *op;
1988
1989 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1990 return NULL;
1991 op = refchain._ob_next;
1992 res = PyList_New(0);
1993 if (res == NULL)
1994 return NULL;
1995 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1996 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001997 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001998 op = op->_ob_next;
1999 if (op == &refchain)
2000 return res;
2001 }
2002 if (PyList_Append(res, op) < 0) {
2003 Py_DECREF(res);
2004 return NULL;
2005 }
2006 op = op->_ob_next;
2007 }
2008 return res;
2009}
2010
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002011#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002012
2013
2014/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00002015PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00002016
2017
2018/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00002019int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002020
2021
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00002022/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00002023
Thomas Wouters334fb892000-07-25 12:56:38 +00002024void *
Fred Drake100814d2000-07-09 15:48:49 +00002025PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002026{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002027 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002028}
2029
Thomas Wouters334fb892000-07-25 12:56:38 +00002030void *
2031PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002032{
Tim Petersaf3e8de2002-04-12 07:22:56 +00002033 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002034}
2035
2036void
Thomas Wouters334fb892000-07-25 12:56:38 +00002037PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002038{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002039 PyMem_FREE(p);
2040}
2041
2042
Guido van Rossum86610361998-04-10 22:32:46 +00002043/* These methods are used to control infinite recursion in repr, str, print,
2044 etc. Container objects that may recursively contain themselves,
2045 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2046 Py_ReprLeave() to avoid infinite recursion.
2047
2048 Py_ReprEnter() returns 0 the first time it is called for a particular
2049 object and 1 every time thereafter. It returns -1 if an exception
2050 occurred. Py_ReprLeave() has no return value.
2051
2052 See dictobject.c and listobject.c for examples of use.
2053*/
2054
2055#define KEY "Py_Repr"
2056
2057int
Fred Drake100814d2000-07-09 15:48:49 +00002058Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002059{
2060 PyObject *dict;
2061 PyObject *list;
2062 int i;
2063
2064 dict = PyThreadState_GetDict();
2065 if (dict == NULL)
2066 return -1;
2067 list = PyDict_GetItemString(dict, KEY);
2068 if (list == NULL) {
2069 list = PyList_New(0);
2070 if (list == NULL)
2071 return -1;
2072 if (PyDict_SetItemString(dict, KEY, list) < 0)
2073 return -1;
2074 Py_DECREF(list);
2075 }
2076 i = PyList_GET_SIZE(list);
2077 while (--i >= 0) {
2078 if (PyList_GET_ITEM(list, i) == obj)
2079 return 1;
2080 }
2081 PyList_Append(list, obj);
2082 return 0;
2083}
2084
2085void
Fred Drake100814d2000-07-09 15:48:49 +00002086Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002087{
2088 PyObject *dict;
2089 PyObject *list;
2090 int i;
2091
2092 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002093 if (dict == NULL)
2094 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002095 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002096 if (list == NULL || !PyList_Check(list))
2097 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002098 i = PyList_GET_SIZE(list);
2099 /* Count backwards because we always expect obj to be list[-1] */
2100 while (--i >= 0) {
2101 if (PyList_GET_ITEM(list, i) == obj) {
2102 PyList_SetSlice(list, i, i + 1, NULL);
2103 break;
2104 }
2105 }
2106}
Guido van Rossumd724b232000-03-13 16:01:29 +00002107
Tim Peters803526b2002-07-07 05:13:56 +00002108/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002109
Tim Peters803526b2002-07-07 05:13:56 +00002110/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002111int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002112
Tim Peters803526b2002-07-07 05:13:56 +00002113/* List of objects that still need to be cleaned up, singly linked via their
2114 * gc headers' gc_prev pointers.
2115 */
2116PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002117
Tim Peters803526b2002-07-07 05:13:56 +00002118/* Add op to the _PyTrash_delete_later list. Called when the current
2119 * call-stack depth gets large. op must be a currently untracked gc'ed
2120 * object, with refcount 0. Py_DECREF must already have been called on it.
2121 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002122void
Fred Drake100814d2000-07-09 15:48:49 +00002123_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002124{
Tim Peters803526b2002-07-07 05:13:56 +00002125 assert(PyObject_IS_GC(op));
2126 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2127 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002128 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002129 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002130}
2131
Tim Peters803526b2002-07-07 05:13:56 +00002132/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2133 * the call-stack unwinds again.
2134 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002135void
Fred Drake100814d2000-07-09 15:48:49 +00002136_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002137{
2138 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002139 PyObject *op = _PyTrash_delete_later;
2140 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002141
Neil Schemenauerf589c052002-03-29 03:05:54 +00002142 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002143 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002144
Tim Peters803526b2002-07-07 05:13:56 +00002145 /* Call the deallocator directly. This used to try to
2146 * fool Py_DECREF into calling it indirectly, but
2147 * Py_DECREF was already called on this object, and in
2148 * assorted non-release builds calling Py_DECREF again ends
2149 * up distorting allocation statistics.
2150 */
2151 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002152 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002153 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002154 --_PyTrash_delete_nesting;
2155 }
2156}