blob: ecc25c7c5ec7ff2d222549f66d1da10c11b8c4a0 [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
Tim Peters78be7992003-03-23 02:51:01 +000020#ifdef Py_TRACE_REFS
21/* Head of doubly-linked list of all objects. */
22static PyObject refchain = {&refchain, &refchain};
23#endif
24
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000025#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000026static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000027extern int tuple_zero_allocs, fast_tuple_allocs;
28extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000029extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000030void
Fred Drake100814d2000-07-09 15:48:49 +000031dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000032{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000033 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000034
35 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000036 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000037 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000038 tp->tp_maxalloc);
39 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
40 fast_tuple_allocs, tuple_zero_allocs);
41 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
42 quick_int_allocs, quick_neg_int_allocs);
43 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
44 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000045}
46
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000047PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000048get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000049{
50 PyTypeObject *tp;
51 PyObject *result;
52 PyObject *v;
53
54 result = PyList_New(0);
55 if (result == NULL)
56 return NULL;
57 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000058 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
59 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000060 if (v == NULL) {
61 Py_DECREF(result);
62 return NULL;
63 }
64 if (PyList_Append(result, v) < 0) {
65 Py_DECREF(v);
66 Py_DECREF(result);
67 return NULL;
68 }
69 Py_DECREF(v);
70 }
71 return result;
72}
73
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074void
Fred Drake100814d2000-07-09 15:48:49 +000075inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076{
Tim Peters6d6c1a32001-08-02 04:15:00 +000077 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +000078 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000079 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000080 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000081 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +000082 /* Note that as of Python 2.2, heap-allocated type objects
83 * can go away, but this code requires that they stay alive
84 * until program exit. That's why we're careful with
85 * refcounts here. type_list gets a new reference to tp,
86 * while ownership of the reference type_list used to hold
87 * (if any) was transferred to tp->tp_next in the line above.
88 * tp is thus effectively immortal after this.
89 */
90 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000091 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +000092#ifdef Py_TRACE_REFS
Tim Peters78be7992003-03-23 02:51:01 +000093 /* Also insert in the doubly-linked list of all objects. */
94 if (tp->_ob_next == NULL) {
95 PyObject *op = (PyObject *)tp;
96 op->_ob_next = refchain._ob_next;
97 op->_ob_prev = &refchain;
98 refchain._ob_next->_ob_prev = op;
99 refchain._ob_next = op;
100 }
101#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000102 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000103 tp->tp_allocs++;
104 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
105 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000106}
107#endif
108
Tim Peters7c321a82002-07-09 02:57:01 +0000109#ifdef Py_REF_DEBUG
110/* Log a fatal error; doesn't return. */
111void
112_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
113{
114 char buf[300];
115
116 PyOS_snprintf(buf, sizeof(buf),
117 "%s:%i object at %p has negative ref count %i",
118 fname, lineno, op, op->ob_refcnt);
119 Py_FatalError(buf);
120}
121
122#endif /* Py_REF_DEBUG */
123
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000124PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000125PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000127 if (op == NULL)
128 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000129 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000131 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 return op;
133}
134
Guido van Rossumb18618d2000-05-03 23:44:39 +0000135PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000136PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000137{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000138 if (op == NULL)
139 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000140 /* Any changes should be reflected in PyObject_INIT_VAR */
141 op->ob_size = size;
142 op->ob_type = tp;
143 _Py_NewReference((PyObject *)op);
144 return op;
145}
146
147PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000148_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000149{
150 PyObject *op;
151 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
152 if (op == NULL)
153 return PyErr_NoMemory();
154 return PyObject_INIT(op, tp);
155}
156
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000157PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000158_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000160 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000161 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000162 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000164 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000165 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000166}
167
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000168/* for binary compatibility with 2.2 */
169#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000170void
Fred Drake100814d2000-07-09 15:48:49 +0000171_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000172{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000173 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Neal Norwitz1a997502003-01-13 20:13:12 +0000176/* Implementation of PyObject_Print with recursion checking */
177static int
178internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179{
Guido van Rossum278ef591991-07-27 21:40:24 +0000180 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000181 if (nesting > 10) {
182 PyErr_SetString(PyExc_RuntimeError, "print recursion");
183 return -1;
184 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000185 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000186 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000187#ifdef USE_STACKCHECK
188 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000189 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000190 return -1;
191 }
192#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000193 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000194 if (op == NULL) {
195 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196 }
Guido van Rossum90933611991-06-07 16:10:43 +0000197 else {
198 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000199 fprintf(fp, "<refcnt %u at %p>",
200 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000201 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000202 PyObject *s;
203 if (flags & Py_PRINT_RAW)
204 s = PyObject_Str(op);
205 else
206 s = PyObject_Repr(op);
207 if (s == NULL)
208 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000209 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000210 ret = internal_print(s, fp, Py_PRINT_RAW,
211 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000212 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000213 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000214 }
Guido van Rossum90933611991-06-07 16:10:43 +0000215 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000216 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000217 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000218 if (ret == 0) {
219 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000220 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000221 clearerr(fp);
222 ret = -1;
223 }
224 }
225 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226}
227
Neal Norwitz1a997502003-01-13 20:13:12 +0000228int
229PyObject_Print(PyObject *op, FILE *fp, int flags)
230{
231 return internal_print(op, fp, flags, 0);
232}
233
234
Barry Warsaw9bf16442001-01-23 16:24:35 +0000235/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000236void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000237{
Barry Warsaweefb1072001-02-22 22:39:18 +0000238 if (op == NULL)
239 fprintf(stderr, "NULL\n");
240 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000241 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000242 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000243 fprintf(stderr, "\n"
244 "type : %s\n"
245 "refcount: %d\n"
246 "address : %p\n",
247 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
248 op->ob_refcnt,
249 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000250 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000251}
Barry Warsaw903138f2001-01-23 16:33:18 +0000252
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000253PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000254PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000256 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000257 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000258#ifdef USE_STACKCHECK
259 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000260 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000261 return NULL;
262 }
263#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000264 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000266 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000267 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000268 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000269 else {
270 PyObject *res;
271 res = (*v->ob_type->tp_repr)(v);
272 if (res == NULL)
273 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000274#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000275 if (PyUnicode_Check(res)) {
276 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000277 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000278 Py_DECREF(res);
279 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000280 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000281 else
282 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000283 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000284#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000285 if (!PyString_Check(res)) {
286 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000287 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000288 res->ob_type->tp_name);
289 Py_DECREF(res);
290 return NULL;
291 }
292 return res;
293 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000294}
295
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000297PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000298{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000299 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000300
Guido van Rossumc6004111993-11-05 10:22:19 +0000301 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000303 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000305 return v;
306 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000307 if (v->ob_type->tp_str == NULL)
308 return PyObject_Repr(v);
309
310 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000311 if (res == NULL)
312 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000313#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000314 if (PyUnicode_Check(res)) {
315 PyObject* str;
316 str = PyUnicode_AsEncodedString(res, NULL, NULL);
317 Py_DECREF(res);
318 if (str)
319 res = str;
320 else
321 return NULL;
322 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000323#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000324 if (!PyString_Check(res)) {
325 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000326 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000327 res->ob_type->tp_name);
328 Py_DECREF(res);
329 return NULL;
330 }
331 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000332}
333
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000334#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000335PyObject *
336PyObject_Unicode(PyObject *v)
337{
338 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000339
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000340 if (v == NULL)
341 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000342 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000343 Py_INCREF(v);
344 return v;
345 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000346 if (PyUnicode_Check(v)) {
347 /* For a Unicode subtype that's not a Unicode object,
348 return a true Unicode object with the same data. */
349 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
350 PyUnicode_GET_SIZE(v));
351 }
352 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000353 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000354 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000355 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000356 else {
357 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000358 static PyObject *unicodestr;
359 /* XXX As soon as we have a tp_unicode slot, we should
360 check this before trying the __unicode__
361 method. */
362 if (unicodestr == NULL) {
363 unicodestr= PyString_InternFromString(
364 "__unicode__");
365 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000366 return NULL;
367 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000368 func = PyObject_GetAttr(v, unicodestr);
369 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000370 res = PyEval_CallObject(func, (PyObject *)NULL);
371 Py_DECREF(func);
372 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000373 else {
374 PyErr_Clear();
375 if (v->ob_type->tp_str != NULL)
376 res = (*v->ob_type->tp_str)(v);
377 else
378 res = PyObject_Repr(v);
379 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000380 }
381 if (res == NULL)
382 return NULL;
383 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000384 PyObject *str;
385 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000386 Py_DECREF(res);
387 if (str)
388 res = str;
389 else
390 return NULL;
391 }
392 return res;
393}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000394#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000395
396
Guido van Rossuma4073002002-05-31 20:03:54 +0000397/* Helper to warn about deprecated tp_compare return values. Return:
398 -2 for an exception;
399 -1 if v < w;
400 0 if v == w;
401 1 if v > w.
402 (This function cannot return 2.)
403*/
404static int
405adjust_tp_compare(int c)
406{
407 if (PyErr_Occurred()) {
408 if (c != -1 && c != -2) {
409 PyObject *t, *v, *tb;
410 PyErr_Fetch(&t, &v, &tb);
411 if (PyErr_Warn(PyExc_RuntimeWarning,
412 "tp_compare didn't return -1 or -2 "
413 "for exception") < 0) {
414 Py_XDECREF(t);
415 Py_XDECREF(v);
416 Py_XDECREF(tb);
417 }
418 else
419 PyErr_Restore(t, v, tb);
420 }
421 return -2;
422 }
423 else if (c < -1 || c > 1) {
424 if (PyErr_Warn(PyExc_RuntimeWarning,
425 "tp_compare didn't return -1, 0 or 1") < 0)
426 return -2;
427 else
428 return c < -1 ? -1 : 1;
429 }
430 else {
431 assert(c >= -1 && c <= 1);
432 return c;
433 }
434}
435
436
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000437/* Macro to get the tp_richcompare field of a type if defined */
438#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
439 ? (t)->tp_richcompare : NULL)
440
Guido van Rossume797ec12001-01-17 15:24:28 +0000441/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
442static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000443
Guido van Rossume797ec12001-01-17 15:24:28 +0000444/* Try a genuine rich comparison, returning an object. Return:
445 NULL for exception;
446 NotImplemented if this particular rich comparison is not implemented or
447 undefined;
448 some object not equal to NotImplemented if it is implemented
449 (this latter object may not be a Boolean).
450*/
451static PyObject *
452try_rich_compare(PyObject *v, PyObject *w, int op)
453{
454 richcmpfunc f;
455 PyObject *res;
456
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000457 if (v->ob_type != w->ob_type &&
458 PyType_IsSubtype(w->ob_type, v->ob_type) &&
459 (f = RICHCOMPARE(w->ob_type)) != NULL) {
460 res = (*f)(w, v, swapped_op[op]);
461 if (res != Py_NotImplemented)
462 return res;
463 Py_DECREF(res);
464 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000465 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000466 res = (*f)(v, w, op);
467 if (res != Py_NotImplemented)
468 return res;
469 Py_DECREF(res);
470 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000471 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000472 return (*f)(w, v, swapped_op[op]);
473 }
474 res = Py_NotImplemented;
475 Py_INCREF(res);
476 return res;
477}
478
479/* Try a genuine rich comparison, returning an int. Return:
480 -1 for exception (including the case where try_rich_compare() returns an
481 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000482 0 if the outcome is false;
483 1 if the outcome is true;
484 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000485*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000486static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000487try_rich_compare_bool(PyObject *v, PyObject *w, int op)
488{
489 PyObject *res;
490 int ok;
491
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000492 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000493 return 2; /* Shortcut, avoid INCREF+DECREF */
494 res = try_rich_compare(v, w, op);
495 if (res == NULL)
496 return -1;
497 if (res == Py_NotImplemented) {
498 Py_DECREF(res);
499 return 2;
500 }
501 ok = PyObject_IsTrue(res);
502 Py_DECREF(res);
503 return ok;
504}
505
506/* Try rich comparisons to determine a 3-way comparison. Return:
507 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000508 -1 if v < w;
509 0 if v == w;
510 1 if v > w;
511 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000512*/
513static int
514try_rich_to_3way_compare(PyObject *v, PyObject *w)
515{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000516 static struct { int op; int outcome; } tries[3] = {
517 /* Try this operator, and if it is true, use this outcome: */
518 {Py_EQ, 0},
519 {Py_LT, -1},
520 {Py_GT, 1},
521 };
522 int i;
523
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000524 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000525 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000526
527 for (i = 0; i < 3; i++) {
528 switch (try_rich_compare_bool(v, w, tries[i].op)) {
529 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000530 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000531 case 1:
532 return tries[i].outcome;
533 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000534 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000535
536 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000537}
538
539/* Try a 3-way comparison, returning an int. Return:
540 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000541 -1 if v < w;
542 0 if v == w;
543 1 if v > w;
544 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000545*/
546static int
547try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000548{
549 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000550 cmpfunc f;
551
552 /* Comparisons involving instances are given to instance_compare,
553 which has the same return conventions as this function. */
554
Guido van Rossumab3b0342001-09-18 20:38:53 +0000555 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000556 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000557 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000558 if (PyInstance_Check(w))
559 return (*w->ob_type->tp_compare)(v, w);
560
Guido van Rossumab3b0342001-09-18 20:38:53 +0000561 /* If both have the same (non-NULL) tp_compare, use it. */
562 if (f != NULL && f == w->ob_type->tp_compare) {
563 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000564 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000565 }
566
567 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
568 if (f == _PyObject_SlotCompare ||
569 w->ob_type->tp_compare == _PyObject_SlotCompare)
570 return _PyObject_SlotCompare(v, w);
571
Guido van Rossume797ec12001-01-17 15:24:28 +0000572 /* Try coercion; if it fails, give up */
573 c = PyNumber_CoerceEx(&v, &w);
574 if (c < 0)
575 return -2;
576 if (c > 0)
577 return 2;
578
579 /* Try v's comparison, if defined */
580 if ((f = v->ob_type->tp_compare) != NULL) {
581 c = (*f)(v, w);
582 Py_DECREF(v);
583 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000584 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000585 }
586
587 /* Try w's comparison, if defined */
588 if ((f = w->ob_type->tp_compare) != NULL) {
589 c = (*f)(w, v); /* swapped! */
590 Py_DECREF(v);
591 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000592 c = adjust_tp_compare(c);
593 if (c >= -1)
594 return -c; /* Swapped! */
595 else
596 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000597 }
598
599 /* No comparison defined */
600 Py_DECREF(v);
601 Py_DECREF(w);
602 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000603}
604
Guido van Rossume797ec12001-01-17 15:24:28 +0000605/* Final fallback 3-way comparison, returning an int. Return:
606 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000607 -1 if v < w;
608 0 if v == w;
609 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000610*/
611static int
612default_3way_compare(PyObject *v, PyObject *w)
613{
614 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000615 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000616
617 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000618 /* When comparing these pointers, they must be cast to
619 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
620 * uintptr_t). ANSI specifies that pointer compares other
621 * than == and != to non-related structures are undefined.
622 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000623 Py_uintptr_t vv = (Py_uintptr_t)v;
624 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000625 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
626 }
627
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000628#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000629 /* Special case for Unicode */
630 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
631 c = PyUnicode_Compare(v, w);
632 if (!PyErr_Occurred())
633 return c;
634 /* TypeErrors are ignored: if Unicode coercion fails due
635 to one of the arguments not having the right type, we
636 continue as defined by the coercion protocol (see
637 above). Luckily, decoding errors are reported as
638 ValueErrors and are not masked by this technique. */
639 if (!PyErr_ExceptionMatches(PyExc_TypeError))
640 return -2;
641 PyErr_Clear();
642 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000643#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000644
Guido van Rossum0871e932001-01-22 19:28:09 +0000645 /* None is smaller than anything */
646 if (v == Py_None)
647 return -1;
648 if (w == Py_None)
649 return 1;
650
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000651 /* different type: compare type names; numbers are smaller */
652 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000653 vname = "";
654 else
655 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000656 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000657 wname = "";
658 else
659 wname = w->ob_type->tp_name;
660 c = strcmp(vname, wname);
661 if (c < 0)
662 return -1;
663 if (c > 0)
664 return 1;
665 /* Same type name, or (more likely) incomparable numeric types */
666 return ((Py_uintptr_t)(v->ob_type) < (
667 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000668}
669
670#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
671
Tim Peters6d60b2e2001-05-07 20:53:51 +0000672/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000673 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000674 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000675 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000676 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000677 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000678 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000679*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000680static int
Fred Drake100814d2000-07-09 15:48:49 +0000681do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000682{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000683 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000684 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000685
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000686 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000687 && (f = v->ob_type->tp_compare) != NULL) {
688 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000689 if (PyInstance_Check(v)) {
690 /* Instance tp_compare has a different signature.
691 But if it returns undefined we fall through. */
692 if (c != 2)
693 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000694 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000695 }
696 else
697 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000698 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000699 /* We only get here if one of the following is true:
700 a) v and w have different types
701 b) v and w have the same type, which doesn't have tp_compare
702 c) v and w are instances, and either __cmp__ is not defined or
703 __cmp__ returns NotImplemented
704 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000705 c = try_rich_to_3way_compare(v, w);
706 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000707 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000708 c = try_3way_compare(v, w);
709 if (c < 2)
710 return c;
711 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000712}
713
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000714/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000715 some types) and decremented on exit. If the count exceeds the
716 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000717
718 This is a tunable parameter that should only affect the performance
719 of comparisons, nothing else. Setting it high makes comparing deeply
720 nested non-cyclical data structures faster, but makes comparing cyclical
721 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000722*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000723#define NESTING_LIMIT 20
724
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000725static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000726
727static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000728get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000729{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000730 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000731 PyObject *tstate_dict, *inprogress;
732
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000733 if (key == NULL) {
734 key = PyString_InternFromString("cmp_state");
735 if (key == NULL)
736 return NULL;
737 }
738
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000739 tstate_dict = PyThreadState_GetDict();
740 if (tstate_dict == NULL) {
741 PyErr_BadInternalCall();
742 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000743 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000744
Tim Peters803526b2002-07-07 05:13:56 +0000745 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000746 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000747 inprogress = PyDict_New();
748 if (inprogress == NULL)
749 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000750 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000751 Py_DECREF(inprogress);
752 return NULL;
753 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000754 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000755 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000756
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000757 return inprogress;
758}
759
Tim Peters4440f222003-01-20 16:54:59 +0000760/* If the comparison "v op w" is already in progress in this thread, returns
761 * a borrowed reference to Py_None (the caller must not decref).
762 * If it's not already in progress, returns "a token" which must eventually
763 * be passed to delete_token(). The caller must not decref this either
764 * (delete_token decrefs it). The token must not survive beyond any point
765 * where v or w may die.
766 * If an error occurs (out-of-memory), returns NULL.
767 */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000768static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000769check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000770{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000771 PyObject *inprogress;
772 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000773 Py_uintptr_t iv = (Py_uintptr_t)v;
774 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000775 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000776
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000777 inprogress = get_inprogress_dict();
778 if (inprogress == NULL)
779 return NULL;
780
781 token = PyTuple_New(3);
782 if (token == NULL)
783 return NULL;
784
785 if (iv <= iw) {
786 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
787 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
788 if (op >= 0)
789 op = swapped_op[op];
790 } else {
791 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
792 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
793 }
794 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
795 if (x == NULL || y == NULL || z == NULL) {
796 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000797 return NULL;
798 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000799
800 if (PyDict_GetItem(inprogress, token) != NULL) {
801 Py_DECREF(token);
802 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000803 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000804
805 if (PyDict_SetItem(inprogress, token, token) < 0) {
806 Py_DECREF(token);
807 return NULL;
808 }
809
810 return token;
811}
812
813static void
814delete_token(PyObject *token)
815{
816 PyObject *inprogress;
817
818 if (token == NULL || token == Py_None)
819 return;
820 inprogress = get_inprogress_dict();
821 if (inprogress == NULL)
822 PyErr_Clear();
823 else
824 PyDict_DelItem(inprogress, token);
825 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000826}
827
Tim Petersc99213f2001-11-04 05:57:16 +0000828/* Compare v to w. Return
829 -1 if v < w or exception (PyErr_Occurred() true in latter case).
830 0 if v == w.
831 1 if v > w.
832 XXX The docs (C API manual) say the return value is undefined in case
833 XXX of error.
834*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000835int
Fred Drake100814d2000-07-09 15:48:49 +0000836PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000838 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000839 int result;
840
Jack Jansend49cbe12000-08-22 21:52:51 +0000841#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000842 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000843 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000844 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000845 }
846#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000847 if (v == NULL || w == NULL) {
848 PyErr_BadInternalCall();
849 return -1;
850 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000851 if (v == w)
852 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000853 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000854 compare_nesting++;
855 if (compare_nesting > NESTING_LIMIT &&
Tim Peters4440f222003-01-20 16:54:59 +0000856 (vtp->tp_as_mapping || vtp->tp_as_sequence) &&
857 !PyString_CheckExact(v) &&
858 !PyTuple_CheckExact(v)) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000859 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000860 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000861
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000862 if (token == NULL) {
863 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000864 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000865 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000866 /* already comparing these objects. assume
867 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000868 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000869 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000870 else {
871 result = do_cmp(v, w);
872 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000873 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000874 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000875 else {
876 result = do_cmp(v, w);
877 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000878 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000879 return result < 0 ? -1 : result;
880}
881
Tim Petersc99213f2001-11-04 05:57:16 +0000882/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000883static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000884convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000885{
Guido van Rossume797ec12001-01-17 15:24:28 +0000886 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000887 switch (op) {
888 case Py_LT: c = c < 0; break;
889 case Py_LE: c = c <= 0; break;
890 case Py_EQ: c = c == 0; break;
891 case Py_NE: c = c != 0; break;
892 case Py_GT: c = c > 0; break;
893 case Py_GE: c = c >= 0; break;
894 }
895 result = c ? Py_True : Py_False;
896 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000897 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000898}
Tim Peters803526b2002-07-07 05:13:56 +0000899
Tim Petersc99213f2001-11-04 05:57:16 +0000900/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
901 Return
902 NULL if error
903 Py_True if v op w
904 Py_False if not (v op w)
905*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000906static PyObject *
907try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
908{
909 int c;
910
911 c = try_3way_compare(v, w);
912 if (c >= 2)
913 c = default_3way_compare(v, w);
914 if (c <= -2)
915 return NULL;
916 return convert_3way_to_object(op, c);
917}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000918
Tim Petersc99213f2001-11-04 05:57:16 +0000919/* Do rich comparison on v and w. Return
920 NULL if error
921 Else a new reference to an object other than Py_NotImplemented, usually(?):
922 Py_True if v op w
923 Py_False if not (v op w)
924*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000925static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000926do_richcmp(PyObject *v, PyObject *w, int op)
927{
928 PyObject *res;
929
930 res = try_rich_compare(v, w, op);
931 if (res != Py_NotImplemented)
932 return res;
933 Py_DECREF(res);
934
935 return try_3way_to_rich_compare(v, w, op);
936}
937
Tim Petersc99213f2001-11-04 05:57:16 +0000938/* Return:
939 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000940 some object not equal to NotImplemented if it is implemented
941 (this latter object may not be a Boolean).
942*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000943PyObject *
944PyObject_RichCompare(PyObject *v, PyObject *w, int op)
945{
946 PyObject *res;
947
948 assert(Py_LT <= op && op <= Py_GE);
949
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000950 compare_nesting++;
951 if (compare_nesting > NESTING_LIMIT &&
Tim Peters4440f222003-01-20 16:54:59 +0000952 (v->ob_type->tp_as_mapping || v->ob_type->tp_as_sequence) &&
953 !PyString_CheckExact(v) &&
954 !PyTuple_CheckExact(v)) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000955 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000956 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000957 if (token == NULL) {
958 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000959 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000960 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000961 else if (token == Py_None) {
962 /* already comparing these objects with this operator.
963 assume they're equal until shown otherwise */
964 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000965 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000966 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000967 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000968 else {
969 PyErr_SetString(PyExc_ValueError,
970 "can't order recursive values");
971 res = NULL;
972 }
973 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000974 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000975 else {
976 res = do_richcmp(v, w, op);
977 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000978 }
Tim Peters67754e92001-11-04 07:29:31 +0000979 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000980 }
Tim Peters67754e92001-11-04 07:29:31 +0000981
982 /* No nesting extremism.
983 If the types are equal, and not old-style instances, try to
984 get out cheap (don't bother with coercions etc.). */
985 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
986 cmpfunc fcmp;
987 richcmpfunc frich = RICHCOMPARE(v->ob_type);
988 /* If the type has richcmp, try it first. try_rich_compare
989 tries it two-sided, which is not needed since we've a
990 single type only. */
991 if (frich != NULL) {
992 res = (*frich)(v, w, op);
993 if (res != Py_NotImplemented)
994 goto Done;
995 Py_DECREF(res);
996 }
997 /* No richcmp, or this particular richmp not implemented.
998 Try 3-way cmp. */
999 fcmp = v->ob_type->tp_compare;
1000 if (fcmp != NULL) {
1001 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +00001002 c = adjust_tp_compare(c);
1003 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +00001004 res = NULL;
1005 goto Done;
1006 }
1007 res = convert_3way_to_object(op, c);
1008 goto Done;
1009 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001010 }
Tim Peters67754e92001-11-04 07:29:31 +00001011
1012 /* Fast path not taken, or couldn't deliver a useful result. */
1013 res = do_richcmp(v, w, op);
1014Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001015 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +00001016 return res;
1017}
1018
Tim Petersde9725f2001-05-05 10:06:17 +00001019/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +00001020int
1021PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
1022{
1023 PyObject *res = PyObject_RichCompare(v, w, op);
1024 int ok;
1025
1026 if (res == NULL)
1027 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +00001028 if (PyBool_Check(res))
1029 ok = (res == Py_True);
1030 else
1031 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +00001032 Py_DECREF(res);
1033 return ok;
1034}
Fred Drake13634cf2000-06-29 19:17:04 +00001035
1036/* Set of hash utility functions to help maintaining the invariant that
1037 iff a==b then hash(a)==hash(b)
1038
1039 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1040*/
1041
1042long
Fred Drake100814d2000-07-09 15:48:49 +00001043_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001044{
Tim Peters39dce292000-08-15 03:34:48 +00001045 double intpart, fractpart;
1046 int expo;
1047 long hipart;
1048 long x; /* the final hash value */
1049 /* This is designed so that Python numbers of different types
1050 * that compare equal hash to the same value; otherwise comparisons
1051 * of mapping keys will turn out weird.
1052 */
1053
1054#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1055{
1056 extended e;
1057 fractpart = modf(v, &e);
1058 intpart = e;
1059}
1060#else
1061 fractpart = modf(v, &intpart);
1062#endif
1063 if (fractpart == 0.0) {
1064 /* This must return the same hash as an equal int or long. */
1065 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1066 /* Convert to long and use its hash. */
1067 PyObject *plong; /* converted to Python long */
1068 if (Py_IS_INFINITY(intpart))
1069 /* can't convert to long int -- arbitrary */
1070 v = v < 0 ? -271828.0 : 314159.0;
1071 plong = PyLong_FromDouble(v);
1072 if (plong == NULL)
1073 return -1;
1074 x = PyObject_Hash(plong);
1075 Py_DECREF(plong);
1076 return x;
1077 }
1078 /* Fits in a C long == a Python int, so is its own hash. */
1079 x = (long)intpart;
1080 if (x == -1)
1081 x = -2;
1082 return x;
1083 }
1084 /* The fractional part is non-zero, so we don't have to worry about
1085 * making this match the hash of some other type.
1086 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001087 * Since the VAX D double format has 56 mantissa bits, which is the
1088 * most of any double format in use, each of these parts may have as
1089 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001090 * So, assuming sizeof(long) >= 4, each part can be broken into two
1091 * longs; frexp and multiplication are used to do that.
1092 * Also, since the Cray double format has 15 exponent bits, which is
1093 * the most of any double format in use, shifting the exponent field
1094 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001095 */
Tim Peters39dce292000-08-15 03:34:48 +00001096 v = frexp(v, &expo);
1097 v *= 2147483648.0; /* 2**31 */
1098 hipart = (long)v; /* take the top 32 bits */
1099 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1100 x = hipart + (long)v + (expo << 15);
1101 if (x == -1)
1102 x = -2;
1103 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001104}
1105
1106long
Fred Drake100814d2000-07-09 15:48:49 +00001107_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001108{
1109#if SIZEOF_LONG >= SIZEOF_VOID_P
1110 return (long)p;
1111#else
1112 /* convert to a Python long and hash that */
1113 PyObject* longobj;
1114 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001115
Fred Drake13634cf2000-06-29 19:17:04 +00001116 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1117 x = -1;
1118 goto finally;
1119 }
1120 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001121
Fred Drake13634cf2000-06-29 19:17:04 +00001122finally:
1123 Py_XDECREF(longobj);
1124 return x;
1125#endif
1126}
1127
1128
Guido van Rossum9bfef441993-03-29 10:43:31 +00001129long
Fred Drake100814d2000-07-09 15:48:49 +00001130PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001131{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001132 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001133 if (tp->tp_hash != NULL)
1134 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001135 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001136 return _Py_HashPointer(v); /* Use address as hash value */
1137 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001138 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001139 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001140 return -1;
1141}
1142
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001143PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001144PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001145{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001146 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001147
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001149 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 w = PyString_InternFromString(name);
1151 if (w == NULL)
1152 return NULL;
1153 res = PyObject_GetAttr(v, w);
1154 Py_XDECREF(w);
1155 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001156}
1157
1158int
Fred Drake100814d2000-07-09 15:48:49 +00001159PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001160{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001161 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001162 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001163 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001164 return 1;
1165 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001166 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001167 return 0;
1168}
1169
1170int
Fred Drake100814d2000-07-09 15:48:49 +00001171PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001172{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173 PyObject *s;
1174 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001175
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001177 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001178 s = PyString_InternFromString(name);
1179 if (s == NULL)
1180 return -1;
1181 res = PyObject_SetAttr(v, s, w);
1182 Py_XDECREF(s);
1183 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001184}
1185
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001186PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001187PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001188{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 PyTypeObject *tp = v->ob_type;
1190
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001191 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001192#ifdef Py_USING_UNICODE
1193 /* The Unicode to string conversion is done here because the
1194 existing tp_getattro slots expect a string object as name
1195 and we wouldn't want to break those. */
1196 if (PyUnicode_Check(name)) {
1197 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1198 if (name == NULL)
1199 return NULL;
1200 }
1201 else
1202#endif
1203 {
1204 PyErr_SetString(PyExc_TypeError,
1205 "attribute name must be string");
1206 return NULL;
1207 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001208 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001209 if (tp->tp_getattro != NULL)
1210 return (*tp->tp_getattro)(v, name);
1211 if (tp->tp_getattr != NULL)
1212 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1213 PyErr_Format(PyExc_AttributeError,
1214 "'%.50s' object has no attribute '%.400s'",
1215 tp->tp_name, PyString_AS_STRING(name));
1216 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001217}
1218
1219int
Fred Drake100814d2000-07-09 15:48:49 +00001220PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001221{
1222 PyObject *res = PyObject_GetAttr(v, name);
1223 if (res != NULL) {
1224 Py_DECREF(res);
1225 return 1;
1226 }
1227 PyErr_Clear();
1228 return 0;
1229}
1230
1231int
Fred Drake100814d2000-07-09 15:48:49 +00001232PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001233{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001235 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001236
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001237 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001238#ifdef Py_USING_UNICODE
1239 /* The Unicode to string conversion is done here because the
1240 existing tp_setattro slots expect a string object as name
1241 and we wouldn't want to break those. */
1242 if (PyUnicode_Check(name)) {
1243 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1244 if (name == NULL)
1245 return -1;
1246 }
Tim Peters803526b2002-07-07 05:13:56 +00001247 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001248#endif
1249 {
1250 PyErr_SetString(PyExc_TypeError,
1251 "attribute name must be string");
1252 return -1;
1253 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001254 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 else
1256 Py_INCREF(name);
1257
1258 PyString_InternInPlace(&name);
1259 if (tp->tp_setattro != NULL) {
1260 err = (*tp->tp_setattro)(v, name, value);
1261 Py_DECREF(name);
1262 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001263 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264 if (tp->tp_setattr != NULL) {
1265 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1266 Py_DECREF(name);
1267 return err;
1268 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001269 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001270 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1271 PyErr_Format(PyExc_TypeError,
1272 "'%.100s' object has no attributes "
1273 "(%s .%.100s)",
1274 tp->tp_name,
1275 value==NULL ? "del" : "assign to",
1276 PyString_AS_STRING(name));
1277 else
1278 PyErr_Format(PyExc_TypeError,
1279 "'%.100s' object has only read-only attributes "
1280 "(%s .%.100s)",
1281 tp->tp_name,
1282 value==NULL ? "del" : "assign to",
1283 PyString_AS_STRING(name));
1284 return -1;
1285}
1286
1287/* Helper to get a pointer to an object's __dict__ slot, if any */
1288
1289PyObject **
1290_PyObject_GetDictPtr(PyObject *obj)
1291{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292 long dictoffset;
1293 PyTypeObject *tp = obj->ob_type;
1294
1295 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1296 return NULL;
1297 dictoffset = tp->tp_dictoffset;
1298 if (dictoffset == 0)
1299 return NULL;
1300 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001301 int tsize;
1302 size_t size;
1303
1304 tsize = ((PyVarObject *)obj)->ob_size;
1305 if (tsize < 0)
1306 tsize = -tsize;
1307 size = _PyObject_VAR_SIZE(tp, tsize);
1308
Tim Peters6d483d32001-10-06 21:27:34 +00001309 dictoffset += (long)size;
1310 assert(dictoffset > 0);
1311 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312 }
1313 return (PyObject **) ((char *)obj + dictoffset);
1314}
1315
1316/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1317
1318PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001319PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001320{
1321 Py_INCREF(obj);
1322 return obj;
1323}
1324
1325PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1327{
1328 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001329 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001330 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001332 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333 PyObject **dictptr;
1334
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001335 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001336#ifdef Py_USING_UNICODE
1337 /* The Unicode to string conversion is done here because the
1338 existing tp_setattro slots expect a string object as name
1339 and we wouldn't want to break those. */
1340 if (PyUnicode_Check(name)) {
1341 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1342 if (name == NULL)
1343 return NULL;
1344 }
Tim Peters803526b2002-07-07 05:13:56 +00001345 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001346#endif
1347 {
1348 PyErr_SetString(PyExc_TypeError,
1349 "attribute name must be string");
1350 return NULL;
1351 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001352 }
1353 else
1354 Py_INCREF(name);
1355
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001357 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001358 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 }
1360
Guido van Rossum056fbf42002-08-19 19:22:50 +00001361 /* Inline _PyType_Lookup */
1362 {
1363 int i, n;
1364 PyObject *mro, *base, *dict;
1365
1366 /* Look in tp_dict of types in MRO */
1367 mro = tp->tp_mro;
1368 assert(mro != NULL);
1369 assert(PyTuple_Check(mro));
1370 n = PyTuple_GET_SIZE(mro);
1371 for (i = 0; i < n; i++) {
1372 base = PyTuple_GET_ITEM(mro, i);
1373 if (PyClass_Check(base))
1374 dict = ((PyClassObject *)base)->cl_dict;
1375 else {
1376 assert(PyType_Check(base));
1377 dict = ((PyTypeObject *)base)->tp_dict;
1378 }
1379 assert(dict && PyDict_Check(dict));
1380 descr = PyDict_GetItem(dict, name);
1381 if (descr != NULL)
1382 break;
1383 }
1384 }
1385
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001387 if (descr != NULL &&
1388 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001389 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001390 if (f != NULL && PyDescr_IsData(descr)) {
1391 res = f(descr, obj, (PyObject *)obj->ob_type);
1392 goto done;
1393 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001394 }
1395
Guido van Rossumc66ff442002-08-19 16:50:48 +00001396 /* Inline _PyObject_GetDictPtr */
1397 dictoffset = tp->tp_dictoffset;
1398 if (dictoffset != 0) {
1399 PyObject *dict;
1400 if (dictoffset < 0) {
1401 int tsize;
1402 size_t size;
1403
1404 tsize = ((PyVarObject *)obj)->ob_size;
1405 if (tsize < 0)
1406 tsize = -tsize;
1407 size = _PyObject_VAR_SIZE(tp, tsize);
1408
1409 dictoffset += (long)size;
1410 assert(dictoffset > 0);
1411 assert(dictoffset % SIZEOF_VOID_P == 0);
1412 }
1413 dictptr = (PyObject **) ((char *)obj + dictoffset);
1414 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001415 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001416 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001417 if (res != NULL) {
1418 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001419 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001420 }
1421 }
1422 }
1423
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001424 if (f != NULL) {
1425 res = f(descr, obj, (PyObject *)obj->ob_type);
1426 goto done;
1427 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001428
1429 if (descr != NULL) {
1430 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001431 res = descr;
1432 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001433 }
1434
1435 PyErr_Format(PyExc_AttributeError,
1436 "'%.50s' object has no attribute '%.400s'",
1437 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001438 done:
1439 Py_DECREF(name);
1440 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001441}
1442
1443int
1444PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1445{
1446 PyTypeObject *tp = obj->ob_type;
1447 PyObject *descr;
1448 descrsetfunc f;
1449 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001450 int res = -1;
1451
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001452 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001453#ifdef Py_USING_UNICODE
1454 /* The Unicode to string conversion is done here because the
1455 existing tp_setattro slots expect a string object as name
1456 and we wouldn't want to break those. */
1457 if (PyUnicode_Check(name)) {
1458 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1459 if (name == NULL)
1460 return -1;
1461 }
Tim Peters803526b2002-07-07 05:13:56 +00001462 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001463#endif
1464 {
1465 PyErr_SetString(PyExc_TypeError,
1466 "attribute name must be string");
1467 return -1;
1468 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001469 }
1470 else
1471 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472
1473 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001474 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001475 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 }
1477
1478 descr = _PyType_Lookup(tp, name);
1479 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001480 if (descr != NULL &&
1481 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001482 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001483 if (f != NULL && PyDescr_IsData(descr)) {
1484 res = f(descr, obj, value);
1485 goto done;
1486 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001487 }
1488
1489 dictptr = _PyObject_GetDictPtr(obj);
1490 if (dictptr != NULL) {
1491 PyObject *dict = *dictptr;
1492 if (dict == NULL && value != NULL) {
1493 dict = PyDict_New();
1494 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001495 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001496 *dictptr = dict;
1497 }
1498 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001499 if (value == NULL)
1500 res = PyDict_DelItem(dict, name);
1501 else
1502 res = PyDict_SetItem(dict, name, value);
1503 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1504 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001505 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506 }
1507 }
1508
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001509 if (f != NULL) {
1510 res = f(descr, obj, value);
1511 goto done;
1512 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001513
1514 if (descr == NULL) {
1515 PyErr_Format(PyExc_AttributeError,
1516 "'%.50s' object has no attribute '%.400s'",
1517 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001518 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001519 }
1520
1521 PyErr_Format(PyExc_AttributeError,
1522 "'%.50s' object attribute '%.400s' is read-only",
1523 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001524 done:
1525 Py_DECREF(name);
1526 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001527}
1528
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001529/* Test a value used as condition, e.g., in a for or if statement.
1530 Return -1 if an error occurred */
1531
1532int
Fred Drake100814d2000-07-09 15:48:49 +00001533PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001534{
1535 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001536 if (v == Py_True)
1537 return 1;
1538 if (v == Py_False)
1539 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001540 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001541 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001542 else if (v->ob_type->tp_as_number != NULL &&
1543 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001544 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001545 else if (v->ob_type->tp_as_mapping != NULL &&
1546 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001547 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001548 else if (v->ob_type->tp_as_sequence != NULL &&
1549 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001550 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1551 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001552 return 1;
1553 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001554}
1555
Tim Peters803526b2002-07-07 05:13:56 +00001556/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001557 Return -1 if an error occurred */
1558
1559int
Fred Drake100814d2000-07-09 15:48:49 +00001560PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001561{
1562 int res;
1563 res = PyObject_IsTrue(v);
1564 if (res < 0)
1565 return res;
1566 return res == 0;
1567}
1568
Guido van Rossum5524a591995-01-10 15:26:20 +00001569/* Coerce two numeric types to the "larger" one.
1570 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001571 Return value:
1572 -1 if an error occurred;
1573 0 if the coercion succeeded (and then the reference counts are increased);
1574 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001575*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001576int
Fred Drake100814d2000-07-09 15:48:49 +00001577PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001578{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001579 register PyObject *v = *pv;
1580 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001581 int res;
1582
Guido van Rossum517c7d42002-04-26 02:49:14 +00001583 /* Shortcut only for old-style types */
1584 if (v->ob_type == w->ob_type &&
1585 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1586 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001587 Py_INCREF(v);
1588 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001589 return 0;
1590 }
1591 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1592 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1593 if (res <= 0)
1594 return res;
1595 }
1596 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1597 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1598 if (res <= 0)
1599 return res;
1600 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001601 return 1;
1602}
1603
Guido van Rossume797ec12001-01-17 15:24:28 +00001604/* Coerce two numeric types to the "larger" one.
1605 Increment the reference count on each argument.
1606 Return -1 and raise an exception if no coercion is possible
1607 (and then no reference count is incremented).
1608*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001609int
Fred Drake100814d2000-07-09 15:48:49 +00001610PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001611{
1612 int err = PyNumber_CoerceEx(pv, pw);
1613 if (err <= 0)
1614 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001615 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001616 return -1;
1617}
1618
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001619
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001620/* Test whether an object can be called */
1621
1622int
Fred Drake100814d2000-07-09 15:48:49 +00001623PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001624{
1625 if (x == NULL)
1626 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001627 if (PyInstance_Check(x)) {
1628 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001629 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001630 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001631 return 0;
1632 }
1633 /* Could test recursively but don't, for fear of endless
1634 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001635 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001636 return 1;
1637 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001638 else {
1639 return x->ob_type->tp_call != NULL;
1640 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001641}
1642
Tim Peters7eea37e2001-09-04 22:08:56 +00001643/* Helper for PyObject_Dir.
1644 Merge the __dict__ of aclass into dict, and recursively also all
1645 the __dict__s of aclass's base classes. The order of merging isn't
1646 defined, as it's expected that only the final set of dict keys is
1647 interesting.
1648 Return 0 on success, -1 on error.
1649*/
1650
1651static int
1652merge_class_dict(PyObject* dict, PyObject* aclass)
1653{
1654 PyObject *classdict;
1655 PyObject *bases;
1656
1657 assert(PyDict_Check(dict));
1658 assert(aclass);
1659
1660 /* Merge in the type's dict (if any). */
1661 classdict = PyObject_GetAttrString(aclass, "__dict__");
1662 if (classdict == NULL)
1663 PyErr_Clear();
1664 else {
1665 int status = PyDict_Update(dict, classdict);
1666 Py_DECREF(classdict);
1667 if (status < 0)
1668 return -1;
1669 }
1670
1671 /* Recursively merge in the base types' (if any) dicts. */
1672 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001673 if (bases == NULL)
1674 PyErr_Clear();
1675 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001676 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001677 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001678 n = PySequence_Size(bases); /* This better be right */
1679 if (n < 0)
1680 PyErr_Clear();
1681 else {
1682 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001683 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001684 PyObject *base = PySequence_GetItem(bases, i);
1685 if (base == NULL) {
1686 Py_DECREF(bases);
1687 return -1;
1688 }
Tim Peters18e70832003-02-05 19:35:19 +00001689 status = merge_class_dict(dict, base);
1690 Py_DECREF(base);
1691 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001692 Py_DECREF(bases);
1693 return -1;
1694 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001695 }
1696 }
1697 Py_DECREF(bases);
1698 }
1699 return 0;
1700}
1701
Tim Peters305b5852001-09-17 02:38:46 +00001702/* Helper for PyObject_Dir.
1703 If obj has an attr named attrname that's a list, merge its string
1704 elements into keys of dict.
1705 Return 0 on success, -1 on error. Errors due to not finding the attr,
1706 or the attr not being a list, are suppressed.
1707*/
1708
1709static int
1710merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1711{
1712 PyObject *list;
1713 int result = 0;
1714
1715 assert(PyDict_Check(dict));
1716 assert(obj);
1717 assert(attrname);
1718
1719 list = PyObject_GetAttrString(obj, attrname);
1720 if (list == NULL)
1721 PyErr_Clear();
1722
1723 else if (PyList_Check(list)) {
1724 int i;
1725 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1726 PyObject *item = PyList_GET_ITEM(list, i);
1727 if (PyString_Check(item)) {
1728 result = PyDict_SetItem(dict, item, Py_None);
1729 if (result < 0)
1730 break;
1731 }
1732 }
1733 }
1734
1735 Py_XDECREF(list);
1736 return result;
1737}
1738
Tim Peters7eea37e2001-09-04 22:08:56 +00001739/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1740 docstring, which should be kept in synch with this implementation. */
1741
1742PyObject *
1743PyObject_Dir(PyObject *arg)
1744{
1745 /* Set exactly one of these non-NULL before the end. */
1746 PyObject *result = NULL; /* result list */
1747 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1748
1749 /* If NULL arg, return the locals. */
1750 if (arg == NULL) {
1751 PyObject *locals = PyEval_GetLocals();
1752 if (locals == NULL)
1753 goto error;
1754 result = PyDict_Keys(locals);
1755 if (result == NULL)
1756 goto error;
1757 }
1758
1759 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001760 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001761 masterdict = PyObject_GetAttrString(arg, "__dict__");
1762 if (masterdict == NULL)
1763 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001764 if (!PyDict_Check(masterdict)) {
1765 PyErr_SetString(PyExc_TypeError,
1766 "module.__dict__ is not a dictionary");
1767 goto error;
1768 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001769 }
1770
1771 /* Elif some form of type or class, grab its dict and its bases.
1772 We deliberately don't suck up its __class__, as methods belonging
1773 to the metaclass would probably be more confusing than helpful. */
1774 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1775 masterdict = PyDict_New();
1776 if (masterdict == NULL)
1777 goto error;
1778 if (merge_class_dict(masterdict, arg) < 0)
1779 goto error;
1780 }
1781
1782 /* Else look at its dict, and the attrs reachable from its class. */
1783 else {
1784 PyObject *itsclass;
1785 /* Create a dict to start with. CAUTION: Not everything
1786 responding to __dict__ returns a dict! */
1787 masterdict = PyObject_GetAttrString(arg, "__dict__");
1788 if (masterdict == NULL) {
1789 PyErr_Clear();
1790 masterdict = PyDict_New();
1791 }
1792 else if (!PyDict_Check(masterdict)) {
1793 Py_DECREF(masterdict);
1794 masterdict = PyDict_New();
1795 }
1796 else {
1797 /* The object may have returned a reference to its
1798 dict, so copy it to avoid mutating it. */
1799 PyObject *temp = PyDict_Copy(masterdict);
1800 Py_DECREF(masterdict);
1801 masterdict = temp;
1802 }
1803 if (masterdict == NULL)
1804 goto error;
1805
Tim Peters305b5852001-09-17 02:38:46 +00001806 /* Merge in __members__ and __methods__ (if any).
1807 XXX Would like this to go away someday; for now, it's
1808 XXX needed to get at im_self etc of method objects. */
1809 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1810 goto error;
1811 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1812 goto error;
1813
Tim Peters7eea37e2001-09-04 22:08:56 +00001814 /* Merge in attrs reachable from its class.
1815 CAUTION: Not all objects have a __class__ attr. */
1816 itsclass = PyObject_GetAttrString(arg, "__class__");
1817 if (itsclass == NULL)
1818 PyErr_Clear();
1819 else {
1820 int status = merge_class_dict(masterdict, itsclass);
1821 Py_DECREF(itsclass);
1822 if (status < 0)
1823 goto error;
1824 }
1825 }
1826
1827 assert((result == NULL) ^ (masterdict == NULL));
1828 if (masterdict != NULL) {
1829 /* The result comes from its keys. */
1830 assert(result == NULL);
1831 result = PyDict_Keys(masterdict);
1832 if (result == NULL)
1833 goto error;
1834 }
1835
1836 assert(result);
1837 if (PyList_Sort(result) != 0)
1838 goto error;
1839 else
1840 goto normal_return;
1841
1842 error:
1843 Py_XDECREF(result);
1844 result = NULL;
1845 /* fall through */
1846 normal_return:
1847 Py_XDECREF(masterdict);
1848 return result;
1849}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001850
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001851/*
1852NoObject is usable as a non-NULL undefined value, used by the macro None.
1853There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001854so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001855(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001856*/
1857
Guido van Rossum0c182a11992-03-27 17:26:13 +00001858/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001859static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001860none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001861{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001862 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001863}
1864
Barry Warsaw9bf16442001-01-23 16:24:35 +00001865/* ARGUSED */
1866static void
Tim Peters803526b2002-07-07 05:13:56 +00001867none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001868{
1869 /* This should never get called, but we also don't want to SEGV if
1870 * we accidently decref None out of existance.
1871 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001872 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001873}
1874
1875
Guido van Rossumba21a492001-08-16 08:17:26 +00001876static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001877 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001878 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001879 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001880 0,
1881 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001882 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001883 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001884 0, /*tp_getattr*/
1885 0, /*tp_setattr*/
1886 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001887 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001888 0, /*tp_as_number*/
1889 0, /*tp_as_sequence*/
1890 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001891 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001892};
1893
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001894PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001895 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001896};
1897
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001898/* NotImplemented is an object that can be used to signal that an
1899 operation is not implemented for the given type combination. */
1900
1901static PyObject *
1902NotImplemented_repr(PyObject *op)
1903{
1904 return PyString_FromString("NotImplemented");
1905}
1906
1907static PyTypeObject PyNotImplemented_Type = {
1908 PyObject_HEAD_INIT(&PyType_Type)
1909 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001910 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001911 0,
1912 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001913 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001914 0, /*tp_print*/
1915 0, /*tp_getattr*/
1916 0, /*tp_setattr*/
1917 0, /*tp_compare*/
1918 (reprfunc)NotImplemented_repr, /*tp_repr*/
1919 0, /*tp_as_number*/
1920 0, /*tp_as_sequence*/
1921 0, /*tp_as_mapping*/
1922 0, /*tp_hash */
1923};
1924
1925PyObject _Py_NotImplementedStruct = {
1926 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1927};
1928
Guido van Rossumba21a492001-08-16 08:17:26 +00001929void
1930_Py_ReadyTypes(void)
1931{
1932 if (PyType_Ready(&PyType_Type) < 0)
1933 Py_FatalError("Can't initialize 'type'");
1934
Guido van Rossum77f6a652002-04-03 22:41:51 +00001935 if (PyType_Ready(&PyBool_Type) < 0)
1936 Py_FatalError("Can't initialize 'bool'");
1937
Guido van Rossumcacfc072002-05-24 19:01:59 +00001938 if (PyType_Ready(&PyString_Type) < 0)
1939 Py_FatalError("Can't initialize 'str'");
1940
Guido van Rossumba21a492001-08-16 08:17:26 +00001941 if (PyType_Ready(&PyList_Type) < 0)
1942 Py_FatalError("Can't initialize 'list'");
1943
1944 if (PyType_Ready(&PyNone_Type) < 0)
1945 Py_FatalError("Can't initialize type(None)");
1946
1947 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1948 Py_FatalError("Can't initialize type(NotImplemented)");
1949}
1950
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001951
Guido van Rossum84a90321996-05-22 16:34:47 +00001952#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001953
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001954void
Fred Drake100814d2000-07-09 15:48:49 +00001955_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001956{
Tim Peters34592512002-07-11 06:23:50 +00001957 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001958 op->ob_refcnt = 1;
1959 op->_ob_next = refchain._ob_next;
1960 op->_ob_prev = &refchain;
1961 refchain._ob_next->_ob_prev = op;
1962 refchain._ob_next = op;
Tim Peters34592512002-07-11 06:23:50 +00001963 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001964}
1965
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001966void
Fred Drake100814d2000-07-09 15:48:49 +00001967_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001968{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001969#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001970 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001971#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001972 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001973 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001974 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001975 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001977#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001978 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1979 if (p == op)
1980 break;
1981 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001982 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001983 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001984#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001985 op->_ob_next->_ob_prev = op->_ob_prev;
1986 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001987 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001988 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001989}
1990
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001991void
Fred Drake100814d2000-07-09 15:48:49 +00001992_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001993{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001994 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001995 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001996 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001997}
1998
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001999void
Fred Drake100814d2000-07-09 15:48:49 +00002000_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002001{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002002 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00002003 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002004 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
2005 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002006 if (PyObject_Print(op, fp, 0) != 0)
2007 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002008 putc('\n', fp);
2009 }
2010}
2011
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002012PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002013_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002014{
2015 int i, n;
2016 PyObject *t = NULL;
2017 PyObject *res, *op;
2018
2019 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2020 return NULL;
2021 op = refchain._ob_next;
2022 res = PyList_New(0);
2023 if (res == NULL)
2024 return NULL;
2025 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2026 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00002027 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002028 op = op->_ob_next;
2029 if (op == &refchain)
2030 return res;
2031 }
2032 if (PyList_Append(res, op) < 0) {
2033 Py_DECREF(res);
2034 return NULL;
2035 }
2036 op = op->_ob_next;
2037 }
2038 return res;
2039}
2040
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002041#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002042
2043
2044/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00002045PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00002046
2047
2048/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00002049int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002050
2051
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00002052/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00002053
Thomas Wouters334fb892000-07-25 12:56:38 +00002054void *
Fred Drake100814d2000-07-09 15:48:49 +00002055PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002056{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002057 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002058}
2059
Thomas Wouters334fb892000-07-25 12:56:38 +00002060void *
2061PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002062{
Tim Petersaf3e8de2002-04-12 07:22:56 +00002063 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002064}
2065
2066void
Thomas Wouters334fb892000-07-25 12:56:38 +00002067PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002068{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002069 PyMem_FREE(p);
2070}
2071
2072
Guido van Rossum86610361998-04-10 22:32:46 +00002073/* These methods are used to control infinite recursion in repr, str, print,
2074 etc. Container objects that may recursively contain themselves,
2075 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2076 Py_ReprLeave() to avoid infinite recursion.
2077
2078 Py_ReprEnter() returns 0 the first time it is called for a particular
2079 object and 1 every time thereafter. It returns -1 if an exception
2080 occurred. Py_ReprLeave() has no return value.
2081
2082 See dictobject.c and listobject.c for examples of use.
2083*/
2084
2085#define KEY "Py_Repr"
2086
2087int
Fred Drake100814d2000-07-09 15:48:49 +00002088Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002089{
2090 PyObject *dict;
2091 PyObject *list;
2092 int i;
2093
2094 dict = PyThreadState_GetDict();
2095 if (dict == NULL)
2096 return -1;
2097 list = PyDict_GetItemString(dict, KEY);
2098 if (list == NULL) {
2099 list = PyList_New(0);
2100 if (list == NULL)
2101 return -1;
2102 if (PyDict_SetItemString(dict, KEY, list) < 0)
2103 return -1;
2104 Py_DECREF(list);
2105 }
2106 i = PyList_GET_SIZE(list);
2107 while (--i >= 0) {
2108 if (PyList_GET_ITEM(list, i) == obj)
2109 return 1;
2110 }
2111 PyList_Append(list, obj);
2112 return 0;
2113}
2114
2115void
Fred Drake100814d2000-07-09 15:48:49 +00002116Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002117{
2118 PyObject *dict;
2119 PyObject *list;
2120 int i;
2121
2122 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002123 if (dict == NULL)
2124 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002125 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002126 if (list == NULL || !PyList_Check(list))
2127 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002128 i = PyList_GET_SIZE(list);
2129 /* Count backwards because we always expect obj to be list[-1] */
2130 while (--i >= 0) {
2131 if (PyList_GET_ITEM(list, i) == obj) {
2132 PyList_SetSlice(list, i, i + 1, NULL);
2133 break;
2134 }
2135 }
2136}
Guido van Rossumd724b232000-03-13 16:01:29 +00002137
Tim Peters803526b2002-07-07 05:13:56 +00002138/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002139
Tim Peters803526b2002-07-07 05:13:56 +00002140/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002141int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002142
Tim Peters803526b2002-07-07 05:13:56 +00002143/* List of objects that still need to be cleaned up, singly linked via their
2144 * gc headers' gc_prev pointers.
2145 */
2146PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002147
Tim Peters803526b2002-07-07 05:13:56 +00002148/* Add op to the _PyTrash_delete_later list. Called when the current
2149 * call-stack depth gets large. op must be a currently untracked gc'ed
2150 * object, with refcount 0. Py_DECREF must already have been called on it.
2151 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002152void
Fred Drake100814d2000-07-09 15:48:49 +00002153_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002154{
Tim Peters803526b2002-07-07 05:13:56 +00002155 assert(PyObject_IS_GC(op));
2156 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2157 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002158 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002159 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002160}
2161
Tim Peters803526b2002-07-07 05:13:56 +00002162/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2163 * the call-stack unwinds again.
2164 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002165void
Fred Drake100814d2000-07-09 15:48:49 +00002166_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002167{
2168 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002169 PyObject *op = _PyTrash_delete_later;
2170 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002171
Neil Schemenauerf589c052002-03-29 03:05:54 +00002172 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002173 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002174
Tim Peters803526b2002-07-07 05:13:56 +00002175 /* Call the deallocator directly. This used to try to
2176 * fool Py_DECREF into calling it indirectly, but
2177 * Py_DECREF was already called on this object, and in
2178 * assorted non-release builds calling Py_DECREF again ends
2179 * up distorting allocation statistics.
2180 */
2181 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002182 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002183 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002184 --_PyTrash_delete_nesting;
2185 }
2186}