blob: 059b36ab0a60700281766429681b229a42ce7d91 [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};
Tim Peters36eb4df2003-03-23 03:33:13 +000023
24/* Insert op at the fron of the doubly-linked list of all objects. */
25void
26_Py_AddToAllObjects(PyObject *op)
27{
28 op->_ob_next = refchain._ob_next;
29 op->_ob_prev = &refchain;
30 refchain._ob_next->_ob_prev = op;
31 refchain._ob_next = op;
32}
Tim Peters78be7992003-03-23 02:51:01 +000033#endif
34
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000035#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000036static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000037extern int tuple_zero_allocs, fast_tuple_allocs;
38extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000039extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000040void
Fred Drake100814d2000-07-09 15:48:49 +000041dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000042{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000043 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000044
45 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000046 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000047 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000048 tp->tp_maxalloc);
49 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
50 fast_tuple_allocs, tuple_zero_allocs);
51 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
52 quick_int_allocs, quick_neg_int_allocs);
53 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
54 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000055}
56
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000057PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000058get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000059{
60 PyTypeObject *tp;
61 PyObject *result;
62 PyObject *v;
63
64 result = PyList_New(0);
65 if (result == NULL)
66 return NULL;
67 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000068 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
69 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000070 if (v == NULL) {
71 Py_DECREF(result);
72 return NULL;
73 }
74 if (PyList_Append(result, v) < 0) {
75 Py_DECREF(v);
76 Py_DECREF(result);
77 return NULL;
78 }
79 Py_DECREF(v);
80 }
81 return result;
82}
83
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000084void
Fred Drake100814d2000-07-09 15:48:49 +000085inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000086{
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +000088 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000089 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000091 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +000092 /* Note that as of Python 2.2, heap-allocated type objects
93 * can go away, but this code requires that they stay alive
94 * until program exit. That's why we're careful with
95 * refcounts here. type_list gets a new reference to tp,
96 * while ownership of the reference type_list used to hold
97 * (if any) was transferred to tp->tp_next in the line above.
98 * tp is thus effectively immortal after this.
99 */
100 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000101 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000102#ifdef Py_TRACE_REFS
Tim Peters78be7992003-03-23 02:51:01 +0000103 /* Also insert in the doubly-linked list of all objects. */
Tim Peters36eb4df2003-03-23 03:33:13 +0000104 if (tp->_ob_prev == NULL) {
105 assert(tp->_ob_next == NULL);
106 _Py_AddToAllObjects((PyObject *)tp);
Tim Peters78be7992003-03-23 02:51:01 +0000107 }
108#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000109 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110 tp->tp_allocs++;
111 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
112 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000113}
114#endif
115
Tim Peters7c321a82002-07-09 02:57:01 +0000116#ifdef Py_REF_DEBUG
117/* Log a fatal error; doesn't return. */
118void
119_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
120{
121 char buf[300];
122
123 PyOS_snprintf(buf, sizeof(buf),
124 "%s:%i object at %p has negative ref count %i",
125 fname, lineno, op, op->ob_refcnt);
126 Py_FatalError(buf);
127}
128
129#endif /* Py_REF_DEBUG */
130
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000131PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000132PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000134 if (op == NULL)
135 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000136 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 return op;
140}
141
Guido van Rossumb18618d2000-05-03 23:44:39 +0000142PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000143PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000144{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000145 if (op == NULL)
146 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000147 /* Any changes should be reflected in PyObject_INIT_VAR */
148 op->ob_size = size;
149 op->ob_type = tp;
150 _Py_NewReference((PyObject *)op);
151 return op;
152}
153
154PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000155_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000156{
157 PyObject *op;
158 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
159 if (op == NULL)
160 return PyErr_NoMemory();
161 return PyObject_INIT(op, tp);
162}
163
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000164PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000165_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000167 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000168 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000169 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000171 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000172 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000173}
174
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000175/* for binary compatibility with 2.2 */
176#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000177void
Fred Drake100814d2000-07-09 15:48:49 +0000178_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000179{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000180 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
Neal Norwitz1a997502003-01-13 20:13:12 +0000183/* Implementation of PyObject_Print with recursion checking */
184static int
185internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
Guido van Rossum278ef591991-07-27 21:40:24 +0000187 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000188 if (nesting > 10) {
189 PyErr_SetString(PyExc_RuntimeError, "print recursion");
190 return -1;
191 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000193 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000194#ifdef USE_STACKCHECK
195 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000196 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000197 return -1;
198 }
199#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000200 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000201 if (op == NULL) {
202 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203 }
Guido van Rossum90933611991-06-07 16:10:43 +0000204 else {
205 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000206 fprintf(fp, "<refcnt %u at %p>",
207 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000208 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000209 PyObject *s;
210 if (flags & Py_PRINT_RAW)
211 s = PyObject_Str(op);
212 else
213 s = PyObject_Repr(op);
214 if (s == NULL)
215 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000216 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000217 ret = internal_print(s, fp, Py_PRINT_RAW,
218 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000219 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000220 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000221 }
Guido van Rossum90933611991-06-07 16:10:43 +0000222 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000223 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000224 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000225 if (ret == 0) {
226 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000227 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000228 clearerr(fp);
229 ret = -1;
230 }
231 }
232 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233}
234
Neal Norwitz1a997502003-01-13 20:13:12 +0000235int
236PyObject_Print(PyObject *op, FILE *fp, int flags)
237{
238 return internal_print(op, fp, flags, 0);
239}
240
241
Barry Warsaw9bf16442001-01-23 16:24:35 +0000242/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000243void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000244{
Barry Warsaweefb1072001-02-22 22:39:18 +0000245 if (op == NULL)
246 fprintf(stderr, "NULL\n");
247 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000248 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000249 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000250 fprintf(stderr, "\n"
251 "type : %s\n"
252 "refcount: %d\n"
253 "address : %p\n",
254 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
255 op->ob_refcnt,
256 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000257 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000258}
Barry Warsaw903138f2001-01-23 16:33:18 +0000259
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000260PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000261PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000264 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000265#ifdef USE_STACKCHECK
266 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000267 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000268 return NULL;
269 }
270#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000271 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000273 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000274 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000275 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000276 else {
277 PyObject *res;
278 res = (*v->ob_type->tp_repr)(v);
279 if (res == NULL)
280 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000281#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000282 if (PyUnicode_Check(res)) {
283 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000284 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000285 Py_DECREF(res);
286 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000287 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000288 else
289 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000290 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000291#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000292 if (!PyString_Check(res)) {
293 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000294 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000295 res->ob_type->tp_name);
296 Py_DECREF(res);
297 return NULL;
298 }
299 return res;
300 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301}
302
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000304PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000305{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000306 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000307
Guido van Rossumc6004111993-11-05 10:22:19 +0000308 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000310 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000312 return v;
313 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000314 if (v->ob_type->tp_str == NULL)
315 return PyObject_Repr(v);
316
317 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000318 if (res == NULL)
319 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000320#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000321 if (PyUnicode_Check(res)) {
322 PyObject* str;
323 str = PyUnicode_AsEncodedString(res, NULL, NULL);
324 Py_DECREF(res);
325 if (str)
326 res = str;
327 else
328 return NULL;
329 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000330#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000331 if (!PyString_Check(res)) {
332 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000333 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000334 res->ob_type->tp_name);
335 Py_DECREF(res);
336 return NULL;
337 }
338 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000339}
340
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000341#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000342PyObject *
343PyObject_Unicode(PyObject *v)
344{
345 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000346
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000347 if (v == NULL)
348 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000349 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000350 Py_INCREF(v);
351 return v;
352 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000353 if (PyUnicode_Check(v)) {
354 /* For a Unicode subtype that's not a Unicode object,
355 return a true Unicode object with the same data. */
356 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
357 PyUnicode_GET_SIZE(v));
358 }
359 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000360 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000361 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000362 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000363 else {
364 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000365 static PyObject *unicodestr;
366 /* XXX As soon as we have a tp_unicode slot, we should
367 check this before trying the __unicode__
368 method. */
369 if (unicodestr == NULL) {
370 unicodestr= PyString_InternFromString(
371 "__unicode__");
372 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000373 return NULL;
374 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000375 func = PyObject_GetAttr(v, unicodestr);
376 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000377 res = PyEval_CallObject(func, (PyObject *)NULL);
378 Py_DECREF(func);
379 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000380 else {
381 PyErr_Clear();
382 if (v->ob_type->tp_str != NULL)
383 res = (*v->ob_type->tp_str)(v);
384 else
385 res = PyObject_Repr(v);
386 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000387 }
388 if (res == NULL)
389 return NULL;
390 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000391 PyObject *str;
392 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000393 Py_DECREF(res);
394 if (str)
395 res = str;
396 else
397 return NULL;
398 }
399 return res;
400}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000401#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000402
403
Guido van Rossuma4073002002-05-31 20:03:54 +0000404/* Helper to warn about deprecated tp_compare return values. Return:
405 -2 for an exception;
406 -1 if v < w;
407 0 if v == w;
408 1 if v > w.
409 (This function cannot return 2.)
410*/
411static int
412adjust_tp_compare(int c)
413{
414 if (PyErr_Occurred()) {
415 if (c != -1 && c != -2) {
416 PyObject *t, *v, *tb;
417 PyErr_Fetch(&t, &v, &tb);
418 if (PyErr_Warn(PyExc_RuntimeWarning,
419 "tp_compare didn't return -1 or -2 "
420 "for exception") < 0) {
421 Py_XDECREF(t);
422 Py_XDECREF(v);
423 Py_XDECREF(tb);
424 }
425 else
426 PyErr_Restore(t, v, tb);
427 }
428 return -2;
429 }
430 else if (c < -1 || c > 1) {
431 if (PyErr_Warn(PyExc_RuntimeWarning,
432 "tp_compare didn't return -1, 0 or 1") < 0)
433 return -2;
434 else
435 return c < -1 ? -1 : 1;
436 }
437 else {
438 assert(c >= -1 && c <= 1);
439 return c;
440 }
441}
442
443
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000444/* Macro to get the tp_richcompare field of a type if defined */
445#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
446 ? (t)->tp_richcompare : NULL)
447
Guido van Rossume797ec12001-01-17 15:24:28 +0000448/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
449static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000450
Guido van Rossume797ec12001-01-17 15:24:28 +0000451/* Try a genuine rich comparison, returning an object. Return:
452 NULL for exception;
453 NotImplemented if this particular rich comparison is not implemented or
454 undefined;
455 some object not equal to NotImplemented if it is implemented
456 (this latter object may not be a Boolean).
457*/
458static PyObject *
459try_rich_compare(PyObject *v, PyObject *w, int op)
460{
461 richcmpfunc f;
462 PyObject *res;
463
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000464 if (v->ob_type != w->ob_type &&
465 PyType_IsSubtype(w->ob_type, v->ob_type) &&
466 (f = RICHCOMPARE(w->ob_type)) != NULL) {
467 res = (*f)(w, v, swapped_op[op]);
468 if (res != Py_NotImplemented)
469 return res;
470 Py_DECREF(res);
471 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000472 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000473 res = (*f)(v, w, op);
474 if (res != Py_NotImplemented)
475 return res;
476 Py_DECREF(res);
477 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000478 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000479 return (*f)(w, v, swapped_op[op]);
480 }
481 res = Py_NotImplemented;
482 Py_INCREF(res);
483 return res;
484}
485
486/* Try a genuine rich comparison, returning an int. Return:
487 -1 for exception (including the case where try_rich_compare() returns an
488 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000489 0 if the outcome is false;
490 1 if the outcome is true;
491 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000492*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000493static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000494try_rich_compare_bool(PyObject *v, PyObject *w, int op)
495{
496 PyObject *res;
497 int ok;
498
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000499 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000500 return 2; /* Shortcut, avoid INCREF+DECREF */
501 res = try_rich_compare(v, w, op);
502 if (res == NULL)
503 return -1;
504 if (res == Py_NotImplemented) {
505 Py_DECREF(res);
506 return 2;
507 }
508 ok = PyObject_IsTrue(res);
509 Py_DECREF(res);
510 return ok;
511}
512
513/* Try rich comparisons to determine a 3-way comparison. Return:
514 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000515 -1 if v < w;
516 0 if v == w;
517 1 if v > w;
518 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000519*/
520static int
521try_rich_to_3way_compare(PyObject *v, PyObject *w)
522{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000523 static struct { int op; int outcome; } tries[3] = {
524 /* Try this operator, and if it is true, use this outcome: */
525 {Py_EQ, 0},
526 {Py_LT, -1},
527 {Py_GT, 1},
528 };
529 int i;
530
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000531 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000532 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000533
534 for (i = 0; i < 3; i++) {
535 switch (try_rich_compare_bool(v, w, tries[i].op)) {
536 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000537 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000538 case 1:
539 return tries[i].outcome;
540 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000541 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000542
543 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000544}
545
546/* Try a 3-way comparison, returning an int. Return:
547 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000548 -1 if v < w;
549 0 if v == w;
550 1 if v > w;
551 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000552*/
553static int
554try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000555{
556 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000557 cmpfunc f;
558
559 /* Comparisons involving instances are given to instance_compare,
560 which has the same return conventions as this function. */
561
Guido van Rossumab3b0342001-09-18 20:38:53 +0000562 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000563 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000564 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000565 if (PyInstance_Check(w))
566 return (*w->ob_type->tp_compare)(v, w);
567
Guido van Rossumab3b0342001-09-18 20:38:53 +0000568 /* If both have the same (non-NULL) tp_compare, use it. */
569 if (f != NULL && f == w->ob_type->tp_compare) {
570 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000571 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000572 }
573
574 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
575 if (f == _PyObject_SlotCompare ||
576 w->ob_type->tp_compare == _PyObject_SlotCompare)
577 return _PyObject_SlotCompare(v, w);
578
Guido van Rossume797ec12001-01-17 15:24:28 +0000579 /* Try coercion; if it fails, give up */
580 c = PyNumber_CoerceEx(&v, &w);
581 if (c < 0)
582 return -2;
583 if (c > 0)
584 return 2;
585
586 /* Try v's comparison, if defined */
587 if ((f = v->ob_type->tp_compare) != NULL) {
588 c = (*f)(v, w);
589 Py_DECREF(v);
590 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000591 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000592 }
593
594 /* Try w's comparison, if defined */
595 if ((f = w->ob_type->tp_compare) != NULL) {
596 c = (*f)(w, v); /* swapped! */
597 Py_DECREF(v);
598 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000599 c = adjust_tp_compare(c);
600 if (c >= -1)
601 return -c; /* Swapped! */
602 else
603 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000604 }
605
606 /* No comparison defined */
607 Py_DECREF(v);
608 Py_DECREF(w);
609 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000610}
611
Guido van Rossume797ec12001-01-17 15:24:28 +0000612/* Final fallback 3-way comparison, returning an int. Return:
613 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000614 -1 if v < w;
615 0 if v == w;
616 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000617*/
618static int
619default_3way_compare(PyObject *v, PyObject *w)
620{
621 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000622 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000623
624 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000625 /* When comparing these pointers, they must be cast to
626 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
627 * uintptr_t). ANSI specifies that pointer compares other
628 * than == and != to non-related structures are undefined.
629 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000630 Py_uintptr_t vv = (Py_uintptr_t)v;
631 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000632 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
633 }
634
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000635#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000636 /* Special case for Unicode */
637 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
638 c = PyUnicode_Compare(v, w);
639 if (!PyErr_Occurred())
640 return c;
641 /* TypeErrors are ignored: if Unicode coercion fails due
642 to one of the arguments not having the right type, we
643 continue as defined by the coercion protocol (see
644 above). Luckily, decoding errors are reported as
645 ValueErrors and are not masked by this technique. */
646 if (!PyErr_ExceptionMatches(PyExc_TypeError))
647 return -2;
648 PyErr_Clear();
649 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000650#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000651
Guido van Rossum0871e932001-01-22 19:28:09 +0000652 /* None is smaller than anything */
653 if (v == Py_None)
654 return -1;
655 if (w == Py_None)
656 return 1;
657
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000658 /* different type: compare type names; numbers are smaller */
659 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000660 vname = "";
661 else
662 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000663 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000664 wname = "";
665 else
666 wname = w->ob_type->tp_name;
667 c = strcmp(vname, wname);
668 if (c < 0)
669 return -1;
670 if (c > 0)
671 return 1;
672 /* Same type name, or (more likely) incomparable numeric types */
673 return ((Py_uintptr_t)(v->ob_type) < (
674 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000675}
676
677#define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
678
Tim Peters6d60b2e2001-05-07 20:53:51 +0000679/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000680 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000681 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000682 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000683 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000684 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000685 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000686*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000687static int
Fred Drake100814d2000-07-09 15:48:49 +0000688do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000689{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000690 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000691 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000692
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000693 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000694 && (f = v->ob_type->tp_compare) != NULL) {
695 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000696 if (PyInstance_Check(v)) {
697 /* Instance tp_compare has a different signature.
698 But if it returns undefined we fall through. */
699 if (c != 2)
700 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000701 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000702 }
703 else
704 return adjust_tp_compare(c);
Guido van Rossum82fc51c12001-08-16 08:02:45 +0000705 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000706 /* We only get here if one of the following is true:
707 a) v and w have different types
708 b) v and w have the same type, which doesn't have tp_compare
709 c) v and w are instances, and either __cmp__ is not defined or
710 __cmp__ returns NotImplemented
711 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000712 c = try_rich_to_3way_compare(v, w);
713 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000714 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000715 c = try_3way_compare(v, w);
716 if (c < 2)
717 return c;
718 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000719}
720
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000721/* compare_nesting is incremented before calling compare (for
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000722 some types) and decremented on exit. If the count exceeds the
723 nesting limit, enable code to detect circular data structures.
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000724
725 This is a tunable parameter that should only affect the performance
726 of comparisons, nothing else. Setting it high makes comparing deeply
727 nested non-cyclical data structures faster, but makes comparing cyclical
728 data structures slower.
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000729*/
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000730#define NESTING_LIMIT 20
731
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000732static int compare_nesting = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000733
734static PyObject*
Fred Drake100814d2000-07-09 15:48:49 +0000735get_inprogress_dict(void)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000736{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000737 static PyObject *key;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000738 PyObject *tstate_dict, *inprogress;
739
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000740 if (key == NULL) {
741 key = PyString_InternFromString("cmp_state");
742 if (key == NULL)
743 return NULL;
744 }
745
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000746 tstate_dict = PyThreadState_GetDict();
747 if (tstate_dict == NULL) {
748 PyErr_BadInternalCall();
749 return NULL;
Tim Peters803526b2002-07-07 05:13:56 +0000750 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000751
Tim Peters803526b2002-07-07 05:13:56 +0000752 inprogress = PyDict_GetItem(tstate_dict, key);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000753 if (inprogress == NULL) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000754 inprogress = PyDict_New();
755 if (inprogress == NULL)
756 return NULL;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000757 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000758 Py_DECREF(inprogress);
759 return NULL;
760 }
Jeremy Hyltona251ea02000-06-09 16:20:39 +0000761 Py_DECREF(inprogress);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000762 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000763
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000764 return inprogress;
765}
766
Tim Peters4440f222003-01-20 16:54:59 +0000767/* If the comparison "v op w" is already in progress in this thread, returns
768 * a borrowed reference to Py_None (the caller must not decref).
769 * If it's not already in progress, returns "a token" which must eventually
770 * be passed to delete_token(). The caller must not decref this either
771 * (delete_token decrefs it). The token must not survive beyond any point
772 * where v or w may die.
773 * If an error occurs (out-of-memory), returns NULL.
774 */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000775static PyObject *
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000776check_recursion(PyObject *v, PyObject *w, int op)
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000777{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000778 PyObject *inprogress;
779 PyObject *token;
Barry Warsaw9d23a4e2000-08-18 05:01:19 +0000780 Py_uintptr_t iv = (Py_uintptr_t)v;
781 Py_uintptr_t iw = (Py_uintptr_t)w;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000782 PyObject *x, *y, *z;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000783
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000784 inprogress = get_inprogress_dict();
785 if (inprogress == NULL)
786 return NULL;
787
788 token = PyTuple_New(3);
789 if (token == NULL)
790 return NULL;
791
792 if (iv <= iw) {
793 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
794 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
795 if (op >= 0)
796 op = swapped_op[op];
797 } else {
798 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
799 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
800 }
801 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
802 if (x == NULL || y == NULL || z == NULL) {
803 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000804 return NULL;
805 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000806
807 if (PyDict_GetItem(inprogress, token) != NULL) {
808 Py_DECREF(token);
809 return Py_None; /* Without INCREF! */
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000810 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000811
812 if (PyDict_SetItem(inprogress, token, token) < 0) {
813 Py_DECREF(token);
814 return NULL;
815 }
816
817 return token;
818}
819
820static void
821delete_token(PyObject *token)
822{
823 PyObject *inprogress;
824
825 if (token == NULL || token == Py_None)
826 return;
827 inprogress = get_inprogress_dict();
828 if (inprogress == NULL)
829 PyErr_Clear();
830 else
831 PyDict_DelItem(inprogress, token);
832 Py_DECREF(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000833}
834
Tim Petersc99213f2001-11-04 05:57:16 +0000835/* Compare v to w. Return
836 -1 if v < w or exception (PyErr_Occurred() true in latter case).
837 0 if v == w.
838 1 if v > w.
839 XXX The docs (C API manual) say the return value is undefined in case
840 XXX of error.
841*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000842int
Fred Drake100814d2000-07-09 15:48:49 +0000843PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000844{
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000845 PyTypeObject *vtp;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000846 int result;
847
Jack Jansend49cbe12000-08-22 21:52:51 +0000848#if defined(USE_STACKCHECK)
Guido van Rossum9c0a99e2000-08-30 15:53:50 +0000849 if (PyOS_CheckStack()) {
Jack Jansend49cbe12000-08-22 21:52:51 +0000850 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
Jeremy Hylton39a362d2001-10-22 16:30:36 +0000851 return -1;
Jack Jansend49cbe12000-08-22 21:52:51 +0000852 }
853#endif
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000854 if (v == NULL || w == NULL) {
855 PyErr_BadInternalCall();
856 return -1;
857 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000858 if (v == w)
859 return 0;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000860 vtp = v->ob_type;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000861 compare_nesting++;
862 if (compare_nesting > NESTING_LIMIT &&
Tim Peters4440f222003-01-20 16:54:59 +0000863 (vtp->tp_as_mapping || vtp->tp_as_sequence) &&
864 !PyString_CheckExact(v) &&
865 !PyTuple_CheckExact(v)) {
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000866 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000867 PyObject *token = check_recursion(v, w, -1);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000868
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000869 if (token == NULL) {
870 result = -1;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000871 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000872 else if (token == Py_None) {
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000873 /* already comparing these objects. assume
874 they're equal until shown otherwise */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000875 result = 0;
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000876 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000877 else {
878 result = do_cmp(v, w);
879 delete_token(token);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000880 }
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000881 }
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000882 else {
883 result = do_cmp(v, w);
884 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000885 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +0000886 return result < 0 ? -1 : result;
887}
888
Tim Petersc99213f2001-11-04 05:57:16 +0000889/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000890static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000891convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000892{
Guido van Rossume797ec12001-01-17 15:24:28 +0000893 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000894 switch (op) {
895 case Py_LT: c = c < 0; break;
896 case Py_LE: c = c <= 0; break;
897 case Py_EQ: c = c == 0; break;
898 case Py_NE: c = c != 0; break;
899 case Py_GT: c = c > 0; break;
900 case Py_GE: c = c >= 0; break;
901 }
902 result = c ? Py_True : Py_False;
903 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000904 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000905}
Tim Peters803526b2002-07-07 05:13:56 +0000906
Tim Petersc99213f2001-11-04 05:57:16 +0000907/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
908 Return
909 NULL if error
910 Py_True if v op w
911 Py_False if not (v op w)
912*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000913static PyObject *
914try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
915{
916 int c;
917
918 c = try_3way_compare(v, w);
919 if (c >= 2)
920 c = default_3way_compare(v, w);
921 if (c <= -2)
922 return NULL;
923 return convert_3way_to_object(op, c);
924}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000925
Tim Petersc99213f2001-11-04 05:57:16 +0000926/* Do rich comparison on v and w. Return
927 NULL if error
928 Else a new reference to an object other than Py_NotImplemented, usually(?):
929 Py_True if v op w
930 Py_False if not (v op w)
931*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000932static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000933do_richcmp(PyObject *v, PyObject *w, int op)
934{
935 PyObject *res;
936
937 res = try_rich_compare(v, w, op);
938 if (res != Py_NotImplemented)
939 return res;
940 Py_DECREF(res);
941
942 return try_3way_to_rich_compare(v, w, op);
943}
944
Tim Petersc99213f2001-11-04 05:57:16 +0000945/* Return:
946 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000947 some object not equal to NotImplemented if it is implemented
948 (this latter object may not be a Boolean).
949*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000950PyObject *
951PyObject_RichCompare(PyObject *v, PyObject *w, int op)
952{
953 PyObject *res;
954
955 assert(Py_LT <= op && op <= Py_GE);
956
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000957 compare_nesting++;
958 if (compare_nesting > NESTING_LIMIT &&
Tim Peters4440f222003-01-20 16:54:59 +0000959 (v->ob_type->tp_as_mapping || v->ob_type->tp_as_sequence) &&
960 !PyString_CheckExact(v) &&
961 !PyTuple_CheckExact(v)) {
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000962 /* try to detect circular data structures */
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000963 PyObject *token = check_recursion(v, w, op);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000964 if (token == NULL) {
965 res = NULL;
Tim Peters67754e92001-11-04 07:29:31 +0000966 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000967 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000968 else if (token == Py_None) {
969 /* already comparing these objects with this operator.
970 assume they're equal until shown otherwise */
971 if (op == Py_EQ)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000972 res = Py_True;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000973 else if (op == Py_NE)
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000974 res = Py_False;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000975 else {
976 PyErr_SetString(PyExc_ValueError,
977 "can't order recursive values");
978 res = NULL;
979 }
980 Py_XINCREF(res);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000981 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000982 else {
983 res = do_richcmp(v, w, op);
984 delete_token(token);
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000985 }
Tim Peters67754e92001-11-04 07:29:31 +0000986 goto Done;
Guido van Rossume797ec12001-01-17 15:24:28 +0000987 }
Tim Peters67754e92001-11-04 07:29:31 +0000988
989 /* No nesting extremism.
990 If the types are equal, and not old-style instances, try to
991 get out cheap (don't bother with coercions etc.). */
992 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
993 cmpfunc fcmp;
994 richcmpfunc frich = RICHCOMPARE(v->ob_type);
995 /* If the type has richcmp, try it first. try_rich_compare
996 tries it two-sided, which is not needed since we've a
997 single type only. */
998 if (frich != NULL) {
999 res = (*frich)(v, w, op);
1000 if (res != Py_NotImplemented)
1001 goto Done;
1002 Py_DECREF(res);
1003 }
1004 /* No richcmp, or this particular richmp not implemented.
1005 Try 3-way cmp. */
1006 fcmp = v->ob_type->tp_compare;
1007 if (fcmp != NULL) {
1008 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +00001009 c = adjust_tp_compare(c);
1010 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +00001011 res = NULL;
1012 goto Done;
1013 }
1014 res = convert_3way_to_object(op, c);
1015 goto Done;
1016 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001017 }
Tim Peters67754e92001-11-04 07:29:31 +00001018
1019 /* Fast path not taken, or couldn't deliver a useful result. */
1020 res = do_richcmp(v, w, op);
1021Done:
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +00001022 compare_nesting--;
Guido van Rossume797ec12001-01-17 15:24:28 +00001023 return res;
1024}
1025
Tim Petersde9725f2001-05-05 10:06:17 +00001026/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +00001027int
1028PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
1029{
1030 PyObject *res = PyObject_RichCompare(v, w, op);
1031 int ok;
1032
1033 if (res == NULL)
1034 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +00001035 if (PyBool_Check(res))
1036 ok = (res == Py_True);
1037 else
1038 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +00001039 Py_DECREF(res);
1040 return ok;
1041}
Fred Drake13634cf2000-06-29 19:17:04 +00001042
1043/* Set of hash utility functions to help maintaining the invariant that
1044 iff a==b then hash(a)==hash(b)
1045
1046 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1047*/
1048
1049long
Fred Drake100814d2000-07-09 15:48:49 +00001050_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +00001051{
Tim Peters39dce292000-08-15 03:34:48 +00001052 double intpart, fractpart;
1053 int expo;
1054 long hipart;
1055 long x; /* the final hash value */
1056 /* This is designed so that Python numbers of different types
1057 * that compare equal hash to the same value; otherwise comparisons
1058 * of mapping keys will turn out weird.
1059 */
1060
1061#ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1062{
1063 extended e;
1064 fractpart = modf(v, &e);
1065 intpart = e;
1066}
1067#else
1068 fractpart = modf(v, &intpart);
1069#endif
1070 if (fractpart == 0.0) {
1071 /* This must return the same hash as an equal int or long. */
1072 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1073 /* Convert to long and use its hash. */
1074 PyObject *plong; /* converted to Python long */
1075 if (Py_IS_INFINITY(intpart))
1076 /* can't convert to long int -- arbitrary */
1077 v = v < 0 ? -271828.0 : 314159.0;
1078 plong = PyLong_FromDouble(v);
1079 if (plong == NULL)
1080 return -1;
1081 x = PyObject_Hash(plong);
1082 Py_DECREF(plong);
1083 return x;
1084 }
1085 /* Fits in a C long == a Python int, so is its own hash. */
1086 x = (long)intpart;
1087 if (x == -1)
1088 x = -2;
1089 return x;
1090 }
1091 /* The fractional part is non-zero, so we don't have to worry about
1092 * making this match the hash of some other type.
1093 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +00001094 * Since the VAX D double format has 56 mantissa bits, which is the
1095 * most of any double format in use, each of these parts may have as
1096 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +00001097 * So, assuming sizeof(long) >= 4, each part can be broken into two
1098 * longs; frexp and multiplication are used to do that.
1099 * Also, since the Cray double format has 15 exponent bits, which is
1100 * the most of any double format in use, shifting the exponent field
1101 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +00001102 */
Tim Peters39dce292000-08-15 03:34:48 +00001103 v = frexp(v, &expo);
1104 v *= 2147483648.0; /* 2**31 */
1105 hipart = (long)v; /* take the top 32 bits */
1106 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1107 x = hipart + (long)v + (expo << 15);
1108 if (x == -1)
1109 x = -2;
1110 return x;
Fred Drake13634cf2000-06-29 19:17:04 +00001111}
1112
1113long
Fred Drake100814d2000-07-09 15:48:49 +00001114_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +00001115{
1116#if SIZEOF_LONG >= SIZEOF_VOID_P
1117 return (long)p;
1118#else
1119 /* convert to a Python long and hash that */
1120 PyObject* longobj;
1121 long x;
Tim Peters803526b2002-07-07 05:13:56 +00001122
Fred Drake13634cf2000-06-29 19:17:04 +00001123 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1124 x = -1;
1125 goto finally;
1126 }
1127 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +00001128
Fred Drake13634cf2000-06-29 19:17:04 +00001129finally:
1130 Py_XDECREF(longobj);
1131 return x;
1132#endif
1133}
1134
1135
Guido van Rossum9bfef441993-03-29 10:43:31 +00001136long
Fred Drake100814d2000-07-09 15:48:49 +00001137PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001138{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001139 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001140 if (tp->tp_hash != NULL)
1141 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +00001142 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +00001143 return _Py_HashPointer(v); /* Use address as hash value */
1144 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00001145 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001146 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +00001147 return -1;
1148}
1149
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001150PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001151PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001152{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001154
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001156 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157 w = PyString_InternFromString(name);
1158 if (w == NULL)
1159 return NULL;
1160 res = PyObject_GetAttr(v, w);
1161 Py_XDECREF(w);
1162 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001163}
1164
1165int
Fred Drake100814d2000-07-09 15:48:49 +00001166PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001167{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001168 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001169 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001170 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001171 return 1;
1172 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001173 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001174 return 0;
1175}
1176
1177int
Fred Drake100814d2000-07-09 15:48:49 +00001178PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001179{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001180 PyObject *s;
1181 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001182
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001184 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001185 s = PyString_InternFromString(name);
1186 if (s == NULL)
1187 return -1;
1188 res = PyObject_SetAttr(v, s, w);
1189 Py_XDECREF(s);
1190 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001191}
1192
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001193PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001194PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001195{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001196 PyTypeObject *tp = v->ob_type;
1197
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001198 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001199#ifdef Py_USING_UNICODE
1200 /* The Unicode to string conversion is done here because the
1201 existing tp_getattro slots expect a string object as name
1202 and we wouldn't want to break those. */
1203 if (PyUnicode_Check(name)) {
1204 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1205 if (name == NULL)
1206 return NULL;
1207 }
1208 else
1209#endif
1210 {
1211 PyErr_SetString(PyExc_TypeError,
1212 "attribute name must be string");
1213 return NULL;
1214 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001215 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 if (tp->tp_getattro != NULL)
1217 return (*tp->tp_getattro)(v, name);
1218 if (tp->tp_getattr != NULL)
1219 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1220 PyErr_Format(PyExc_AttributeError,
1221 "'%.50s' object has no attribute '%.400s'",
1222 tp->tp_name, PyString_AS_STRING(name));
1223 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001224}
1225
1226int
Fred Drake100814d2000-07-09 15:48:49 +00001227PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001228{
1229 PyObject *res = PyObject_GetAttr(v, name);
1230 if (res != NULL) {
1231 Py_DECREF(res);
1232 return 1;
1233 }
1234 PyErr_Clear();
1235 return 0;
1236}
1237
1238int
Fred Drake100814d2000-07-09 15:48:49 +00001239PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001240{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001242 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001243
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001244 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001245#ifdef Py_USING_UNICODE
1246 /* The Unicode to string conversion is done here because the
1247 existing tp_setattro slots expect a string object as name
1248 and we wouldn't want to break those. */
1249 if (PyUnicode_Check(name)) {
1250 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1251 if (name == NULL)
1252 return -1;
1253 }
Tim Peters803526b2002-07-07 05:13:56 +00001254 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001255#endif
1256 {
1257 PyErr_SetString(PyExc_TypeError,
1258 "attribute name must be string");
1259 return -1;
1260 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001261 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262 else
1263 Py_INCREF(name);
1264
1265 PyString_InternInPlace(&name);
1266 if (tp->tp_setattro != NULL) {
1267 err = (*tp->tp_setattro)(v, name, value);
1268 Py_DECREF(name);
1269 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001270 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271 if (tp->tp_setattr != NULL) {
1272 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1273 Py_DECREF(name);
1274 return err;
1275 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001276 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1278 PyErr_Format(PyExc_TypeError,
1279 "'%.100s' object has no attributes "
1280 "(%s .%.100s)",
1281 tp->tp_name,
1282 value==NULL ? "del" : "assign to",
1283 PyString_AS_STRING(name));
1284 else
1285 PyErr_Format(PyExc_TypeError,
1286 "'%.100s' object has only read-only attributes "
1287 "(%s .%.100s)",
1288 tp->tp_name,
1289 value==NULL ? "del" : "assign to",
1290 PyString_AS_STRING(name));
1291 return -1;
1292}
1293
1294/* Helper to get a pointer to an object's __dict__ slot, if any */
1295
1296PyObject **
1297_PyObject_GetDictPtr(PyObject *obj)
1298{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 long dictoffset;
1300 PyTypeObject *tp = obj->ob_type;
1301
1302 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1303 return NULL;
1304 dictoffset = tp->tp_dictoffset;
1305 if (dictoffset == 0)
1306 return NULL;
1307 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001308 int tsize;
1309 size_t size;
1310
1311 tsize = ((PyVarObject *)obj)->ob_size;
1312 if (tsize < 0)
1313 tsize = -tsize;
1314 size = _PyObject_VAR_SIZE(tp, tsize);
1315
Tim Peters6d483d32001-10-06 21:27:34 +00001316 dictoffset += (long)size;
1317 assert(dictoffset > 0);
1318 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001319 }
1320 return (PyObject **) ((char *)obj + dictoffset);
1321}
1322
1323/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1324
1325PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001326PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001327{
1328 Py_INCREF(obj);
1329 return obj;
1330}
1331
1332PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001333PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1334{
1335 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001336 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001337 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001339 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001340 PyObject **dictptr;
1341
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001342 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001343#ifdef Py_USING_UNICODE
1344 /* The Unicode to string conversion is done here because the
1345 existing tp_setattro slots expect a string object as name
1346 and we wouldn't want to break those. */
1347 if (PyUnicode_Check(name)) {
1348 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1349 if (name == NULL)
1350 return NULL;
1351 }
Tim Peters803526b2002-07-07 05:13:56 +00001352 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001353#endif
1354 {
1355 PyErr_SetString(PyExc_TypeError,
1356 "attribute name must be string");
1357 return NULL;
1358 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 }
1360 else
1361 Py_INCREF(name);
1362
Tim Peters6d6c1a32001-08-02 04:15:00 +00001363 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001364 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001365 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366 }
1367
Guido van Rossum056fbf42002-08-19 19:22:50 +00001368 /* Inline _PyType_Lookup */
1369 {
1370 int i, n;
1371 PyObject *mro, *base, *dict;
1372
1373 /* Look in tp_dict of types in MRO */
1374 mro = tp->tp_mro;
1375 assert(mro != NULL);
1376 assert(PyTuple_Check(mro));
1377 n = PyTuple_GET_SIZE(mro);
1378 for (i = 0; i < n; i++) {
1379 base = PyTuple_GET_ITEM(mro, i);
1380 if (PyClass_Check(base))
1381 dict = ((PyClassObject *)base)->cl_dict;
1382 else {
1383 assert(PyType_Check(base));
1384 dict = ((PyTypeObject *)base)->tp_dict;
1385 }
1386 assert(dict && PyDict_Check(dict));
1387 descr = PyDict_GetItem(dict, name);
1388 if (descr != NULL)
1389 break;
1390 }
1391 }
1392
Tim Peters6d6c1a32001-08-02 04:15:00 +00001393 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001394 if (descr != NULL &&
1395 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001396 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001397 if (f != NULL && PyDescr_IsData(descr)) {
1398 res = f(descr, obj, (PyObject *)obj->ob_type);
1399 goto done;
1400 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001401 }
1402
Guido van Rossumc66ff442002-08-19 16:50:48 +00001403 /* Inline _PyObject_GetDictPtr */
1404 dictoffset = tp->tp_dictoffset;
1405 if (dictoffset != 0) {
1406 PyObject *dict;
1407 if (dictoffset < 0) {
1408 int tsize;
1409 size_t size;
1410
1411 tsize = ((PyVarObject *)obj)->ob_size;
1412 if (tsize < 0)
1413 tsize = -tsize;
1414 size = _PyObject_VAR_SIZE(tp, tsize);
1415
1416 dictoffset += (long)size;
1417 assert(dictoffset > 0);
1418 assert(dictoffset % SIZEOF_VOID_P == 0);
1419 }
1420 dictptr = (PyObject **) ((char *)obj + dictoffset);
1421 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001422 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001423 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424 if (res != NULL) {
1425 Py_INCREF(res);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001426 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001427 }
1428 }
1429 }
1430
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001431 if (f != NULL) {
1432 res = f(descr, obj, (PyObject *)obj->ob_type);
1433 goto done;
1434 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001435
1436 if (descr != NULL) {
1437 Py_INCREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001438 res = descr;
1439 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440 }
1441
1442 PyErr_Format(PyExc_AttributeError,
1443 "'%.50s' object has no attribute '%.400s'",
1444 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001445 done:
1446 Py_DECREF(name);
1447 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001448}
1449
1450int
1451PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1452{
1453 PyTypeObject *tp = obj->ob_type;
1454 PyObject *descr;
1455 descrsetfunc f;
1456 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001457 int res = -1;
1458
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001459 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001460#ifdef Py_USING_UNICODE
1461 /* The Unicode to string conversion is done here because the
1462 existing tp_setattro slots expect a string object as name
1463 and we wouldn't want to break those. */
1464 if (PyUnicode_Check(name)) {
1465 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1466 if (name == NULL)
1467 return -1;
1468 }
Tim Peters803526b2002-07-07 05:13:56 +00001469 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001470#endif
1471 {
1472 PyErr_SetString(PyExc_TypeError,
1473 "attribute name must be string");
1474 return -1;
1475 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001476 }
1477 else
1478 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001479
1480 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001481 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001482 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001483 }
1484
1485 descr = _PyType_Lookup(tp, name);
1486 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001487 if (descr != NULL &&
1488 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001489 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001490 if (f != NULL && PyDescr_IsData(descr)) {
1491 res = f(descr, obj, value);
1492 goto done;
1493 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001494 }
1495
1496 dictptr = _PyObject_GetDictPtr(obj);
1497 if (dictptr != NULL) {
1498 PyObject *dict = *dictptr;
1499 if (dict == NULL && value != NULL) {
1500 dict = PyDict_New();
1501 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001502 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001503 *dictptr = dict;
1504 }
1505 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001506 if (value == NULL)
1507 res = PyDict_DelItem(dict, name);
1508 else
1509 res = PyDict_SetItem(dict, name, value);
1510 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1511 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001512 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001513 }
1514 }
1515
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001516 if (f != NULL) {
1517 res = f(descr, obj, value);
1518 goto done;
1519 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001520
1521 if (descr == NULL) {
1522 PyErr_Format(PyExc_AttributeError,
1523 "'%.50s' object has no attribute '%.400s'",
1524 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001525 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001526 }
1527
1528 PyErr_Format(PyExc_AttributeError,
1529 "'%.50s' object attribute '%.400s' is read-only",
1530 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001531 done:
1532 Py_DECREF(name);
1533 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001534}
1535
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001536/* Test a value used as condition, e.g., in a for or if statement.
1537 Return -1 if an error occurred */
1538
1539int
Fred Drake100814d2000-07-09 15:48:49 +00001540PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001541{
1542 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001543 if (v == Py_True)
1544 return 1;
1545 if (v == Py_False)
1546 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001547 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001548 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001549 else if (v->ob_type->tp_as_number != NULL &&
1550 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001551 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001552 else if (v->ob_type->tp_as_mapping != NULL &&
1553 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001554 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001555 else if (v->ob_type->tp_as_sequence != NULL &&
1556 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001557 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1558 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001559 return 1;
1560 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001561}
1562
Tim Peters803526b2002-07-07 05:13:56 +00001563/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001564 Return -1 if an error occurred */
1565
1566int
Fred Drake100814d2000-07-09 15:48:49 +00001567PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001568{
1569 int res;
1570 res = PyObject_IsTrue(v);
1571 if (res < 0)
1572 return res;
1573 return res == 0;
1574}
1575
Guido van Rossum5524a591995-01-10 15:26:20 +00001576/* Coerce two numeric types to the "larger" one.
1577 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001578 Return value:
1579 -1 if an error occurred;
1580 0 if the coercion succeeded (and then the reference counts are increased);
1581 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001582*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001583int
Fred Drake100814d2000-07-09 15:48:49 +00001584PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001585{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001586 register PyObject *v = *pv;
1587 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001588 int res;
1589
Guido van Rossum517c7d42002-04-26 02:49:14 +00001590 /* Shortcut only for old-style types */
1591 if (v->ob_type == w->ob_type &&
1592 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1593 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001594 Py_INCREF(v);
1595 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001596 return 0;
1597 }
1598 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1599 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1600 if (res <= 0)
1601 return res;
1602 }
1603 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1604 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1605 if (res <= 0)
1606 return res;
1607 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001608 return 1;
1609}
1610
Guido van Rossume797ec12001-01-17 15:24:28 +00001611/* Coerce two numeric types to the "larger" one.
1612 Increment the reference count on each argument.
1613 Return -1 and raise an exception if no coercion is possible
1614 (and then no reference count is incremented).
1615*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001616int
Fred Drake100814d2000-07-09 15:48:49 +00001617PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001618{
1619 int err = PyNumber_CoerceEx(pv, pw);
1620 if (err <= 0)
1621 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001622 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001623 return -1;
1624}
1625
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001626
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001627/* Test whether an object can be called */
1628
1629int
Fred Drake100814d2000-07-09 15:48:49 +00001630PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001631{
1632 if (x == NULL)
1633 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001634 if (PyInstance_Check(x)) {
1635 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001636 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001637 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001638 return 0;
1639 }
1640 /* Could test recursively but don't, for fear of endless
1641 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001643 return 1;
1644 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001645 else {
1646 return x->ob_type->tp_call != NULL;
1647 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001648}
1649
Tim Peters7eea37e2001-09-04 22:08:56 +00001650/* Helper for PyObject_Dir.
1651 Merge the __dict__ of aclass into dict, and recursively also all
1652 the __dict__s of aclass's base classes. The order of merging isn't
1653 defined, as it's expected that only the final set of dict keys is
1654 interesting.
1655 Return 0 on success, -1 on error.
1656*/
1657
1658static int
1659merge_class_dict(PyObject* dict, PyObject* aclass)
1660{
1661 PyObject *classdict;
1662 PyObject *bases;
1663
1664 assert(PyDict_Check(dict));
1665 assert(aclass);
1666
1667 /* Merge in the type's dict (if any). */
1668 classdict = PyObject_GetAttrString(aclass, "__dict__");
1669 if (classdict == NULL)
1670 PyErr_Clear();
1671 else {
1672 int status = PyDict_Update(dict, classdict);
1673 Py_DECREF(classdict);
1674 if (status < 0)
1675 return -1;
1676 }
1677
1678 /* Recursively merge in the base types' (if any) dicts. */
1679 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001680 if (bases == NULL)
1681 PyErr_Clear();
1682 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001683 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001684 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001685 n = PySequence_Size(bases); /* This better be right */
1686 if (n < 0)
1687 PyErr_Clear();
1688 else {
1689 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001690 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001691 PyObject *base = PySequence_GetItem(bases, i);
1692 if (base == NULL) {
1693 Py_DECREF(bases);
1694 return -1;
1695 }
Tim Peters18e70832003-02-05 19:35:19 +00001696 status = merge_class_dict(dict, base);
1697 Py_DECREF(base);
1698 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001699 Py_DECREF(bases);
1700 return -1;
1701 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001702 }
1703 }
1704 Py_DECREF(bases);
1705 }
1706 return 0;
1707}
1708
Tim Peters305b5852001-09-17 02:38:46 +00001709/* Helper for PyObject_Dir.
1710 If obj has an attr named attrname that's a list, merge its string
1711 elements into keys of dict.
1712 Return 0 on success, -1 on error. Errors due to not finding the attr,
1713 or the attr not being a list, are suppressed.
1714*/
1715
1716static int
1717merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1718{
1719 PyObject *list;
1720 int result = 0;
1721
1722 assert(PyDict_Check(dict));
1723 assert(obj);
1724 assert(attrname);
1725
1726 list = PyObject_GetAttrString(obj, attrname);
1727 if (list == NULL)
1728 PyErr_Clear();
1729
1730 else if (PyList_Check(list)) {
1731 int i;
1732 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1733 PyObject *item = PyList_GET_ITEM(list, i);
1734 if (PyString_Check(item)) {
1735 result = PyDict_SetItem(dict, item, Py_None);
1736 if (result < 0)
1737 break;
1738 }
1739 }
1740 }
1741
1742 Py_XDECREF(list);
1743 return result;
1744}
1745
Tim Peters7eea37e2001-09-04 22:08:56 +00001746/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1747 docstring, which should be kept in synch with this implementation. */
1748
1749PyObject *
1750PyObject_Dir(PyObject *arg)
1751{
1752 /* Set exactly one of these non-NULL before the end. */
1753 PyObject *result = NULL; /* result list */
1754 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1755
1756 /* If NULL arg, return the locals. */
1757 if (arg == NULL) {
1758 PyObject *locals = PyEval_GetLocals();
1759 if (locals == NULL)
1760 goto error;
1761 result = PyDict_Keys(locals);
1762 if (result == NULL)
1763 goto error;
1764 }
1765
1766 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001767 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001768 masterdict = PyObject_GetAttrString(arg, "__dict__");
1769 if (masterdict == NULL)
1770 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001771 if (!PyDict_Check(masterdict)) {
1772 PyErr_SetString(PyExc_TypeError,
1773 "module.__dict__ is not a dictionary");
1774 goto error;
1775 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001776 }
1777
1778 /* Elif some form of type or class, grab its dict and its bases.
1779 We deliberately don't suck up its __class__, as methods belonging
1780 to the metaclass would probably be more confusing than helpful. */
1781 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1782 masterdict = PyDict_New();
1783 if (masterdict == NULL)
1784 goto error;
1785 if (merge_class_dict(masterdict, arg) < 0)
1786 goto error;
1787 }
1788
1789 /* Else look at its dict, and the attrs reachable from its class. */
1790 else {
1791 PyObject *itsclass;
1792 /* Create a dict to start with. CAUTION: Not everything
1793 responding to __dict__ returns a dict! */
1794 masterdict = PyObject_GetAttrString(arg, "__dict__");
1795 if (masterdict == NULL) {
1796 PyErr_Clear();
1797 masterdict = PyDict_New();
1798 }
1799 else if (!PyDict_Check(masterdict)) {
1800 Py_DECREF(masterdict);
1801 masterdict = PyDict_New();
1802 }
1803 else {
1804 /* The object may have returned a reference to its
1805 dict, so copy it to avoid mutating it. */
1806 PyObject *temp = PyDict_Copy(masterdict);
1807 Py_DECREF(masterdict);
1808 masterdict = temp;
1809 }
1810 if (masterdict == NULL)
1811 goto error;
1812
Tim Peters305b5852001-09-17 02:38:46 +00001813 /* Merge in __members__ and __methods__ (if any).
1814 XXX Would like this to go away someday; for now, it's
1815 XXX needed to get at im_self etc of method objects. */
1816 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1817 goto error;
1818 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1819 goto error;
1820
Tim Peters7eea37e2001-09-04 22:08:56 +00001821 /* Merge in attrs reachable from its class.
1822 CAUTION: Not all objects have a __class__ attr. */
1823 itsclass = PyObject_GetAttrString(arg, "__class__");
1824 if (itsclass == NULL)
1825 PyErr_Clear();
1826 else {
1827 int status = merge_class_dict(masterdict, itsclass);
1828 Py_DECREF(itsclass);
1829 if (status < 0)
1830 goto error;
1831 }
1832 }
1833
1834 assert((result == NULL) ^ (masterdict == NULL));
1835 if (masterdict != NULL) {
1836 /* The result comes from its keys. */
1837 assert(result == NULL);
1838 result = PyDict_Keys(masterdict);
1839 if (result == NULL)
1840 goto error;
1841 }
1842
1843 assert(result);
1844 if (PyList_Sort(result) != 0)
1845 goto error;
1846 else
1847 goto normal_return;
1848
1849 error:
1850 Py_XDECREF(result);
1851 result = NULL;
1852 /* fall through */
1853 normal_return:
1854 Py_XDECREF(masterdict);
1855 return result;
1856}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001857
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858/*
1859NoObject is usable as a non-NULL undefined value, used by the macro None.
1860There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001861so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001862(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001863*/
1864
Guido van Rossum0c182a11992-03-27 17:26:13 +00001865/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001866static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001867none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001868{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001869 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001870}
1871
Barry Warsaw9bf16442001-01-23 16:24:35 +00001872/* ARGUSED */
1873static void
Tim Peters803526b2002-07-07 05:13:56 +00001874none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001875{
1876 /* This should never get called, but we also don't want to SEGV if
1877 * we accidently decref None out of existance.
1878 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001879 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001880}
1881
1882
Guido van Rossumba21a492001-08-16 08:17:26 +00001883static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001884 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001885 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001886 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001887 0,
1888 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001889 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001890 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001891 0, /*tp_getattr*/
1892 0, /*tp_setattr*/
1893 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001894 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001895 0, /*tp_as_number*/
1896 0, /*tp_as_sequence*/
1897 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001898 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001899};
1900
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001901PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001902 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001903};
1904
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001905/* NotImplemented is an object that can be used to signal that an
1906 operation is not implemented for the given type combination. */
1907
1908static PyObject *
1909NotImplemented_repr(PyObject *op)
1910{
1911 return PyString_FromString("NotImplemented");
1912}
1913
1914static PyTypeObject PyNotImplemented_Type = {
1915 PyObject_HEAD_INIT(&PyType_Type)
1916 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001917 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001918 0,
1919 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001920 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001921 0, /*tp_print*/
1922 0, /*tp_getattr*/
1923 0, /*tp_setattr*/
1924 0, /*tp_compare*/
1925 (reprfunc)NotImplemented_repr, /*tp_repr*/
1926 0, /*tp_as_number*/
1927 0, /*tp_as_sequence*/
1928 0, /*tp_as_mapping*/
1929 0, /*tp_hash */
1930};
1931
1932PyObject _Py_NotImplementedStruct = {
1933 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1934};
1935
Guido van Rossumba21a492001-08-16 08:17:26 +00001936void
1937_Py_ReadyTypes(void)
1938{
1939 if (PyType_Ready(&PyType_Type) < 0)
1940 Py_FatalError("Can't initialize 'type'");
1941
Guido van Rossum77f6a652002-04-03 22:41:51 +00001942 if (PyType_Ready(&PyBool_Type) < 0)
1943 Py_FatalError("Can't initialize 'bool'");
1944
Guido van Rossumcacfc072002-05-24 19:01:59 +00001945 if (PyType_Ready(&PyString_Type) < 0)
1946 Py_FatalError("Can't initialize 'str'");
1947
Guido van Rossumba21a492001-08-16 08:17:26 +00001948 if (PyType_Ready(&PyList_Type) < 0)
1949 Py_FatalError("Can't initialize 'list'");
1950
1951 if (PyType_Ready(&PyNone_Type) < 0)
1952 Py_FatalError("Can't initialize type(None)");
1953
1954 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1955 Py_FatalError("Can't initialize type(NotImplemented)");
1956}
1957
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001958
Guido van Rossum84a90321996-05-22 16:34:47 +00001959#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001960
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001961void
Fred Drake100814d2000-07-09 15:48:49 +00001962_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001963{
Tim Peters34592512002-07-11 06:23:50 +00001964 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001965 op->ob_refcnt = 1;
Tim Peters36eb4df2003-03-23 03:33:13 +00001966 _Py_AddToAllObjects(op);
Tim Peters34592512002-07-11 06:23:50 +00001967 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001968}
1969
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001970void
Fred Drake100814d2000-07-09 15:48:49 +00001971_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001972{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001973#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001974 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001975#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001976 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001977 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001978 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001979 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001980 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001981#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001982 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1983 if (p == op)
1984 break;
1985 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001986 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001987 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001988#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001989 op->_ob_next->_ob_prev = op->_ob_prev;
1990 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001991 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001992 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001993}
1994
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001995void
Fred Drake100814d2000-07-09 15:48:49 +00001996_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001997{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001998 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001999 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00002000 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002001}
2002
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00002003void
Fred Drake100814d2000-07-09 15:48:49 +00002004_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002005{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002006 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00002007 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002008 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
2009 fprintf(fp, "[%d] ", op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002010 if (PyObject_Print(op, fp, 0) != 0)
2011 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002012 putc('\n', fp);
2013 }
2014}
2015
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002016PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002017_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002018{
2019 int i, n;
2020 PyObject *t = NULL;
2021 PyObject *res, *op;
2022
2023 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2024 return NULL;
2025 op = refchain._ob_next;
2026 res = PyList_New(0);
2027 if (res == NULL)
2028 return NULL;
2029 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2030 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00002031 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002032 op = op->_ob_next;
2033 if (op == &refchain)
2034 return res;
2035 }
2036 if (PyList_Append(res, op) < 0) {
2037 Py_DECREF(res);
2038 return NULL;
2039 }
2040 op = op->_ob_next;
2041 }
2042 return res;
2043}
2044
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002045#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002046
2047
2048/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00002049PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00002050
2051
2052/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00002053int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002054
2055
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00002056/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00002057
Thomas Wouters334fb892000-07-25 12:56:38 +00002058void *
Fred Drake100814d2000-07-09 15:48:49 +00002059PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002060{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002061 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002062}
2063
Thomas Wouters334fb892000-07-25 12:56:38 +00002064void *
2065PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00002066{
Tim Petersaf3e8de2002-04-12 07:22:56 +00002067 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00002068}
2069
2070void
Thomas Wouters334fb892000-07-25 12:56:38 +00002071PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00002072{
Guido van Rossumb18618d2000-05-03 23:44:39 +00002073 PyMem_FREE(p);
2074}
2075
2076
Guido van Rossum86610361998-04-10 22:32:46 +00002077/* These methods are used to control infinite recursion in repr, str, print,
2078 etc. Container objects that may recursively contain themselves,
2079 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2080 Py_ReprLeave() to avoid infinite recursion.
2081
2082 Py_ReprEnter() returns 0 the first time it is called for a particular
2083 object and 1 every time thereafter. It returns -1 if an exception
2084 occurred. Py_ReprLeave() has no return value.
2085
2086 See dictobject.c and listobject.c for examples of use.
2087*/
2088
2089#define KEY "Py_Repr"
2090
2091int
Fred Drake100814d2000-07-09 15:48:49 +00002092Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002093{
2094 PyObject *dict;
2095 PyObject *list;
2096 int i;
2097
2098 dict = PyThreadState_GetDict();
2099 if (dict == NULL)
2100 return -1;
2101 list = PyDict_GetItemString(dict, KEY);
2102 if (list == NULL) {
2103 list = PyList_New(0);
2104 if (list == NULL)
2105 return -1;
2106 if (PyDict_SetItemString(dict, KEY, list) < 0)
2107 return -1;
2108 Py_DECREF(list);
2109 }
2110 i = PyList_GET_SIZE(list);
2111 while (--i >= 0) {
2112 if (PyList_GET_ITEM(list, i) == obj)
2113 return 1;
2114 }
2115 PyList_Append(list, obj);
2116 return 0;
2117}
2118
2119void
Fred Drake100814d2000-07-09 15:48:49 +00002120Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002121{
2122 PyObject *dict;
2123 PyObject *list;
2124 int i;
2125
2126 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002127 if (dict == NULL)
2128 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002129 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002130 if (list == NULL || !PyList_Check(list))
2131 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002132 i = PyList_GET_SIZE(list);
2133 /* Count backwards because we always expect obj to be list[-1] */
2134 while (--i >= 0) {
2135 if (PyList_GET_ITEM(list, i) == obj) {
2136 PyList_SetSlice(list, i, i + 1, NULL);
2137 break;
2138 }
2139 }
2140}
Guido van Rossumd724b232000-03-13 16:01:29 +00002141
Tim Peters803526b2002-07-07 05:13:56 +00002142/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002143
Tim Peters803526b2002-07-07 05:13:56 +00002144/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002145int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002146
Tim Peters803526b2002-07-07 05:13:56 +00002147/* List of objects that still need to be cleaned up, singly linked via their
2148 * gc headers' gc_prev pointers.
2149 */
2150PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002151
Tim Peters803526b2002-07-07 05:13:56 +00002152/* Add op to the _PyTrash_delete_later list. Called when the current
2153 * call-stack depth gets large. op must be a currently untracked gc'ed
2154 * object, with refcount 0. Py_DECREF must already have been called on it.
2155 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002156void
Fred Drake100814d2000-07-09 15:48:49 +00002157_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002158{
Tim Peters803526b2002-07-07 05:13:56 +00002159 assert(PyObject_IS_GC(op));
2160 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2161 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002162 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002163 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002164}
2165
Tim Peters803526b2002-07-07 05:13:56 +00002166/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2167 * the call-stack unwinds again.
2168 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002169void
Fred Drake100814d2000-07-09 15:48:49 +00002170_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002171{
2172 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002173 PyObject *op = _PyTrash_delete_later;
2174 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002175
Neil Schemenauerf589c052002-03-29 03:05:54 +00002176 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002177 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002178
Tim Peters803526b2002-07-07 05:13:56 +00002179 /* Call the deallocator directly. This used to try to
2180 * fool Py_DECREF into calling it indirectly, but
2181 * Py_DECREF was already called on this object, and in
2182 * assorted non-release builds calling Py_DECREF again ends
2183 * up distorting allocation statistics.
2184 */
2185 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002186 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002187 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002188 --_PyTrash_delete_nesting;
2189 }
2190}