blob: 975c967cca7d220c1463bf59a73840407a6c4e15 [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
Tim Peters34592512002-07-11 06:23:50 +00006#ifdef Py_REF_DEBUG
Mark Hammonda2905272002-07-29 13:42:14 +00007long _Py_RefTotal;
Guido van Rossum3f5da241990-12-20 15:06:42 +00008#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Mark Hammonda2905272002-07-29 13:42:14 +000010int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000011
Guido van Rossum3f5da241990-12-20 15:06:42 +000012/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
13 These are used by the individual routines for object creation.
14 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015
Tim Peters78be7992003-03-23 02:51:01 +000016#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000017/* Head of circular doubly-linked list of all objects. These are linked
18 * together via the _ob_prev and _ob_next members of a PyObject, which
19 * exist only in a Py_TRACE_REFS build.
20 */
Tim Peters78be7992003-03-23 02:51:01 +000021static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000022
Tim Peters7571a0f2003-03-23 17:52:28 +000023/* Insert op at the front of the list of all objects. If force is true,
24 * op is added even if _ob_prev and _ob_next are non-NULL already. If
25 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
26 * force should be true if and only if op points to freshly allocated,
27 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000028 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000029 * Note that objects are normally added to the list via _Py_NewReference,
30 * which is called by PyObject_Init. Not all objects are initialized that
31 * way, though; exceptions include statically allocated type objects, and
32 * statically allocated singletons (like Py_True and Py_None).
33 */
Tim Peters36eb4df2003-03-23 03:33:13 +000034void
Tim Peters7571a0f2003-03-23 17:52:28 +000035_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000036{
Tim Peters7571a0f2003-03-23 17:52:28 +000037#ifdef Py_DEBUG
38 if (!force) {
39 /* If it's initialized memory, op must be in or out of
40 * the list unambiguously.
41 */
42 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
43 }
Tim Peters78be7992003-03-23 02:51:01 +000044#endif
Tim Peters7571a0f2003-03-23 17:52:28 +000045 if (force || op->_ob_prev == NULL) {
46 op->_ob_next = refchain._ob_next;
47 op->_ob_prev = &refchain;
48 refchain._ob_next->_ob_prev = op;
49 refchain._ob_next = op;
50 }
51}
52#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000053
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000054#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055static PyTypeObject *type_list;
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000056extern int tuple_zero_allocs, fast_tuple_allocs;
57extern int quick_int_allocs, quick_neg_int_allocs;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000058extern int null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000059void
Fred Drake100814d2000-07-09 15:48:49 +000060dump_counts(void)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000061{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000063
64 for (tp = type_list; tp; tp = tp->tp_next)
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000065 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
Tim Peters6d6c1a32001-08-02 04:15:00 +000066 tp->tp_name, tp->tp_allocs, tp->tp_frees,
Sjoerd Mullender52c1f511993-10-25 08:40:52 +000067 tp->tp_maxalloc);
68 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
69 fast_tuple_allocs, tuple_zero_allocs);
70 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
71 quick_int_allocs, quick_neg_int_allocs);
72 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
73 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000074}
75
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000076PyObject *
Fred Drake100814d2000-07-09 15:48:49 +000077get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000078{
79 PyTypeObject *tp;
80 PyObject *result;
81 PyObject *v;
82
83 result = PyList_New(0);
84 if (result == NULL)
85 return NULL;
86 for (tp = type_list; tp; tp = tp->tp_next) {
Tim Peters6d6c1a32001-08-02 04:15:00 +000087 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
88 tp->tp_frees, tp->tp_maxalloc);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +000089 if (v == NULL) {
90 Py_DECREF(result);
91 return NULL;
92 }
93 if (PyList_Append(result, v) < 0) {
94 Py_DECREF(v);
95 Py_DECREF(result);
96 return NULL;
97 }
98 Py_DECREF(v);
99 }
100 return result;
101}
102
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000103void
Fred Drake100814d2000-07-09 15:48:49 +0000104inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000105{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000106 if (tp->tp_allocs == 0) {
Guido van Rossumd8953cb1995-04-06 14:46:26 +0000107 /* first time; insert in linked list */
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000108 if (tp->tp_next != NULL) /* sanity check */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 Py_FatalError("XXX inc_count sanity check");
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000110 tp->tp_next = type_list;
Tim Petersc6a3ff62002-07-08 22:11:52 +0000111 /* Note that as of Python 2.2, heap-allocated type objects
112 * can go away, but this code requires that they stay alive
113 * until program exit. That's why we're careful with
114 * refcounts here. type_list gets a new reference to tp,
115 * while ownership of the reference type_list used to hold
116 * (if any) was transferred to tp->tp_next in the line above.
117 * tp is thus effectively immortal after this.
118 */
119 Py_INCREF(tp);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000120 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000121#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +0000122 /* Also insert in the doubly-linked list of all objects,
123 * if not already there.
124 */
125 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000126#endif
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000127 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000128 tp->tp_allocs++;
129 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
130 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000131}
132#endif
133
Tim Peters7c321a82002-07-09 02:57:01 +0000134#ifdef Py_REF_DEBUG
135/* Log a fatal error; doesn't return. */
136void
137_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
138{
139 char buf[300];
140
141 PyOS_snprintf(buf, sizeof(buf),
142 "%s:%i object at %p has negative ref count %i",
143 fname, lineno, op, op->ob_refcnt);
144 Py_FatalError(buf);
145}
146
147#endif /* Py_REF_DEBUG */
148
Thomas Heller1328b522004-04-22 17:23:49 +0000149void
150Py_IncRef(PyObject *o)
151{
152 Py_XINCREF(o);
153}
154
155void
156Py_DecRef(PyObject *o)
157{
158 Py_XDECREF(o);
159}
160
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000161PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000162PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000164 if (op == NULL)
165 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000166 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 op->ob_type = tp;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 _Py_NewReference(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 return op;
170}
171
Guido van Rossumb18618d2000-05-03 23:44:39 +0000172PyVarObject *
Fred Drake100814d2000-07-09 15:48:49 +0000173PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000174{
Guido van Rossum6e08c142002-10-11 20:37:24 +0000175 if (op == NULL)
176 return (PyVarObject *) PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000177 /* Any changes should be reflected in PyObject_INIT_VAR */
178 op->ob_size = size;
179 op->ob_type = tp;
180 _Py_NewReference((PyObject *)op);
181 return op;
182}
183
184PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000185_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000186{
187 PyObject *op;
188 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
189 if (op == NULL)
190 return PyErr_NoMemory();
191 return PyObject_INIT(op, tp);
192}
193
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000194PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000195_PyObject_NewVar(PyTypeObject *tp, int nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000197 PyVarObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000198 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Tim Peters6d483d32001-10-06 21:27:34 +0000199 op = (PyVarObject *) PyObject_MALLOC(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200 if (op == NULL)
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000201 return (PyVarObject *)PyErr_NoMemory();
Tim Peters6d483d32001-10-06 21:27:34 +0000202 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000203}
204
Neil Schemenauerbdf0eed2002-04-12 03:08:42 +0000205/* for binary compatibility with 2.2 */
206#undef _PyObject_Del
Guido van Rossumb18618d2000-05-03 23:44:39 +0000207void
Fred Drake100814d2000-07-09 15:48:49 +0000208_PyObject_Del(PyObject *op)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000209{
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000210 PyObject_FREE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211}
212
Neal Norwitz1a997502003-01-13 20:13:12 +0000213/* Implementation of PyObject_Print with recursion checking */
214static int
215internal_print(PyObject *op, FILE *fp, int flags, int nesting)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Guido van Rossum278ef591991-07-27 21:40:24 +0000217 int ret = 0;
Neal Norwitz1a997502003-01-13 20:13:12 +0000218 if (nesting > 10) {
219 PyErr_SetString(PyExc_RuntimeError, "print recursion");
220 return -1;
221 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000222 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000223 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000224#ifdef USE_STACKCHECK
225 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000226 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000227 return -1;
228 }
229#endif
Guido van Rossum687ef6e2000-01-12 16:28:58 +0000230 clearerr(fp); /* Clear any previous error condition */
Guido van Rossum90933611991-06-07 16:10:43 +0000231 if (op == NULL) {
232 fprintf(fp, "<nil>");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233 }
Guido van Rossum90933611991-06-07 16:10:43 +0000234 else {
235 if (op->ob_refcnt <= 0)
Fred Drakea44d3532000-06-30 15:01:00 +0000236 fprintf(fp, "<refcnt %u at %p>",
237 op->ob_refcnt, op);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000238 else if (op->ob_type->tp_print == NULL) {
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000239 PyObject *s;
240 if (flags & Py_PRINT_RAW)
241 s = PyObject_Str(op);
242 else
243 s = PyObject_Repr(op);
244 if (s == NULL)
245 ret = -1;
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000246 else {
Neal Norwitz1a997502003-01-13 20:13:12 +0000247 ret = internal_print(s, fp, Py_PRINT_RAW,
248 nesting+1);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000249 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000250 Py_XDECREF(s);
Guido van Rossum2e8f6141992-09-03 20:32:55 +0000251 }
Guido van Rossum90933611991-06-07 16:10:43 +0000252 else
Guido van Rossum278ef591991-07-27 21:40:24 +0000253 ret = (*op->ob_type->tp_print)(op, fp, flags);
Guido van Rossum90933611991-06-07 16:10:43 +0000254 }
Guido van Rossum278ef591991-07-27 21:40:24 +0000255 if (ret == 0) {
256 if (ferror(fp)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000257 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum278ef591991-07-27 21:40:24 +0000258 clearerr(fp);
259 ret = -1;
260 }
261 }
262 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263}
264
Neal Norwitz1a997502003-01-13 20:13:12 +0000265int
266PyObject_Print(PyObject *op, FILE *fp, int flags)
267{
268 return internal_print(op, fp, flags, 0);
269}
270
271
Barry Warsaw9bf16442001-01-23 16:24:35 +0000272/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Tim Peters803526b2002-07-07 05:13:56 +0000273void _PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000274{
Barry Warsaweefb1072001-02-22 22:39:18 +0000275 if (op == NULL)
276 fprintf(stderr, "NULL\n");
277 else {
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000278 fprintf(stderr, "object : ");
Barry Warsaweefb1072001-02-22 22:39:18 +0000279 (void)PyObject_Print(op, stderr, 0);
Guido van Rossum5f5512d2001-09-14 15:50:08 +0000280 fprintf(stderr, "\n"
281 "type : %s\n"
282 "refcount: %d\n"
283 "address : %p\n",
284 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
285 op->ob_refcnt,
286 op);
Barry Warsaweefb1072001-02-22 22:39:18 +0000287 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000288}
Barry Warsaw903138f2001-01-23 16:33:18 +0000289
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000291PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293 if (PyErr_CheckSignals())
Guido van Rossum90933611991-06-07 16:10:43 +0000294 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000295#ifdef USE_STACKCHECK
296 if (PyOS_CheckStack()) {
Fred Drake661ea262000-10-24 19:57:45 +0000297 PyErr_SetString(PyExc_MemoryError, "stack overflow");
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000298 return NULL;
299 }
300#endif
Guido van Rossum90933611991-06-07 16:10:43 +0000301 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 return PyString_FromString("<NULL>");
Barry Warsaw7ce36942001-08-24 18:34:26 +0000303 else if (v->ob_type->tp_repr == NULL)
Guido van Rossum21922aa2001-08-30 20:26:05 +0000304 return PyString_FromFormat("<%s object at %p>",
Barry Warsaw7ce36942001-08-24 18:34:26 +0000305 v->ob_type->tp_name, v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000306 else {
307 PyObject *res;
308 res = (*v->ob_type->tp_repr)(v);
309 if (res == NULL)
310 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000311#ifdef Py_USING_UNICODE
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000312 if (PyUnicode_Check(res)) {
313 PyObject* str;
Fredrik Lundh2a1e0602000-07-08 17:43:32 +0000314 str = PyUnicode_AsUnicodeEscapeString(res);
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000315 Py_DECREF(res);
316 if (str)
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000317 res = str;
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000318 else
319 return NULL;
Fredrik Lundhefecc7d2000-07-01 14:31:09 +0000320 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000321#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000322 if (!PyString_Check(res)) {
323 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000324 "__repr__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000325 res->ob_type->tp_name);
326 Py_DECREF(res);
327 return NULL;
328 }
329 return res;
330 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331}
332
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000334PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000335{
Guido van Rossum4c08d552000-03-10 22:55:18 +0000336 PyObject *res;
Tim Peters803526b2002-07-07 05:13:56 +0000337
Guido van Rossumc6004111993-11-05 10:22:19 +0000338 if (v == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339 return PyString_FromString("<NULL>");
Tim Peters5a49ade2001-09-11 01:41:59 +0000340 if (PyString_CheckExact(v)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341 Py_INCREF(v);
Guido van Rossumc6004111993-11-05 10:22:19 +0000342 return v;
343 }
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000344 if (v->ob_type->tp_str == NULL)
345 return PyObject_Repr(v);
346
347 res = (*v->ob_type->tp_str)(v);
Guido van Rossum4c08d552000-03-10 22:55:18 +0000348 if (res == NULL)
349 return NULL;
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000350#ifdef Py_USING_UNICODE
Marc-André Lemburg891bc652000-07-03 09:57:53 +0000351 if (PyUnicode_Check(res)) {
352 PyObject* str;
353 str = PyUnicode_AsEncodedString(res, NULL, NULL);
354 Py_DECREF(res);
355 if (str)
356 res = str;
357 else
358 return NULL;
359 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000360#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000361 if (!PyString_Check(res)) {
362 PyErr_Format(PyExc_TypeError,
Guido van Rossum5db862d2000-04-10 12:46:51 +0000363 "__str__ returned non-string (type %.200s)",
Guido van Rossum4c08d552000-03-10 22:55:18 +0000364 res->ob_type->tp_name);
365 Py_DECREF(res);
366 return NULL;
367 }
368 return res;
Guido van Rossumc6004111993-11-05 10:22:19 +0000369}
370
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000371#ifdef Py_USING_UNICODE
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000372PyObject *
373PyObject_Unicode(PyObject *v)
374{
375 PyObject *res;
Brett Cannonc3647ac2005-04-26 03:45:26 +0000376 PyObject *func;
377 static PyObject *unicodestr;
Tim Peters803526b2002-07-07 05:13:56 +0000378
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000379 if (v == NULL)
380 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000381 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000382 Py_INCREF(v);
383 return v;
384 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000385 /* XXX As soon as we have a tp_unicode slot, we should
386 check this before trying the __unicode__
387 method. */
388 if (unicodestr == NULL) {
389 unicodestr= PyString_InternFromString("__unicode__");
390 if (unicodestr == NULL)
391 return NULL;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000392 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000393 func = PyObject_GetAttr(v, unicodestr);
394 if (func != NULL) {
395 res = PyEval_CallObject(func, (PyObject *)NULL);
396 Py_DECREF(func);
397 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000398 else {
Brett Cannonc3647ac2005-04-26 03:45:26 +0000399 PyErr_Clear();
400 if (PyUnicode_Check(v)) {
401 /* For a Unicode subtype that's didn't overwrite __unicode__,
402 return a true Unicode object with the same data. */
403 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
404 PyUnicode_GET_SIZE(v));
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000405 }
Brett Cannonc3647ac2005-04-26 03:45:26 +0000406 if (PyString_CheckExact(v)) {
407 Py_INCREF(v);
408 res = v;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000409 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000410 else {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000411 if (v->ob_type->tp_str != NULL)
412 res = (*v->ob_type->tp_str)(v);
413 else
414 res = PyObject_Repr(v);
415 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000416 }
417 if (res == NULL)
418 return NULL;
419 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000420 PyObject *str;
421 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000422 Py_DECREF(res);
423 if (str)
424 res = str;
425 else
Brett Cannonc3647ac2005-04-26 03:45:26 +0000426 return NULL;
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000427 }
428 return res;
429}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000430#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000431
432
Guido van Rossuma4073002002-05-31 20:03:54 +0000433/* Helper to warn about deprecated tp_compare return values. Return:
434 -2 for an exception;
435 -1 if v < w;
436 0 if v == w;
437 1 if v > w.
438 (This function cannot return 2.)
439*/
440static int
441adjust_tp_compare(int c)
442{
443 if (PyErr_Occurred()) {
444 if (c != -1 && c != -2) {
445 PyObject *t, *v, *tb;
446 PyErr_Fetch(&t, &v, &tb);
447 if (PyErr_Warn(PyExc_RuntimeWarning,
448 "tp_compare didn't return -1 or -2 "
449 "for exception") < 0) {
450 Py_XDECREF(t);
451 Py_XDECREF(v);
452 Py_XDECREF(tb);
453 }
454 else
455 PyErr_Restore(t, v, tb);
456 }
457 return -2;
458 }
459 else if (c < -1 || c > 1) {
460 if (PyErr_Warn(PyExc_RuntimeWarning,
461 "tp_compare didn't return -1, 0 or 1") < 0)
462 return -2;
463 else
464 return c < -1 ? -1 : 1;
465 }
466 else {
467 assert(c >= -1 && c <= 1);
468 return c;
469 }
470}
471
472
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000473/* Macro to get the tp_richcompare field of a type if defined */
474#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
475 ? (t)->tp_richcompare : NULL)
476
Guido van Rossume797ec12001-01-17 15:24:28 +0000477/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000478int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000479
Guido van Rossume797ec12001-01-17 15:24:28 +0000480/* Try a genuine rich comparison, returning an object. Return:
481 NULL for exception;
482 NotImplemented if this particular rich comparison is not implemented or
483 undefined;
484 some object not equal to NotImplemented if it is implemented
485 (this latter object may not be a Boolean).
486*/
487static PyObject *
488try_rich_compare(PyObject *v, PyObject *w, int op)
489{
490 richcmpfunc f;
491 PyObject *res;
492
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000493 if (v->ob_type != w->ob_type &&
494 PyType_IsSubtype(w->ob_type, v->ob_type) &&
495 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000496 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000497 if (res != Py_NotImplemented)
498 return res;
499 Py_DECREF(res);
500 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000501 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000502 res = (*f)(v, w, op);
503 if (res != Py_NotImplemented)
504 return res;
505 Py_DECREF(res);
506 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000507 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000508 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000509 }
510 res = Py_NotImplemented;
511 Py_INCREF(res);
512 return res;
513}
514
515/* Try a genuine rich comparison, returning an int. Return:
516 -1 for exception (including the case where try_rich_compare() returns an
517 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000518 0 if the outcome is false;
519 1 if the outcome is true;
520 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000521*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000522static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000523try_rich_compare_bool(PyObject *v, PyObject *w, int op)
524{
525 PyObject *res;
526 int ok;
527
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000528 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000529 return 2; /* Shortcut, avoid INCREF+DECREF */
530 res = try_rich_compare(v, w, op);
531 if (res == NULL)
532 return -1;
533 if (res == Py_NotImplemented) {
534 Py_DECREF(res);
535 return 2;
536 }
537 ok = PyObject_IsTrue(res);
538 Py_DECREF(res);
539 return ok;
540}
541
542/* Try rich comparisons to determine a 3-way comparison. Return:
543 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000544 -1 if v < w;
545 0 if v == w;
546 1 if v > w;
547 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000548*/
549static int
550try_rich_to_3way_compare(PyObject *v, PyObject *w)
551{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000552 static struct { int op; int outcome; } tries[3] = {
553 /* Try this operator, and if it is true, use this outcome: */
554 {Py_EQ, 0},
555 {Py_LT, -1},
556 {Py_GT, 1},
557 };
558 int i;
559
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000560 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000561 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000562
563 for (i = 0; i < 3; i++) {
564 switch (try_rich_compare_bool(v, w, tries[i].op)) {
565 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000566 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000567 case 1:
568 return tries[i].outcome;
569 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000570 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000571
572 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000573}
574
575/* Try a 3-way comparison, returning an int. Return:
576 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000577 -1 if v < w;
578 0 if v == w;
579 1 if v > w;
580 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000581*/
582static int
583try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000584{
585 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000586 cmpfunc f;
587
588 /* Comparisons involving instances are given to instance_compare,
589 which has the same return conventions as this function. */
590
Guido van Rossumab3b0342001-09-18 20:38:53 +0000591 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000592 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000593 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000594 if (PyInstance_Check(w))
595 return (*w->ob_type->tp_compare)(v, w);
596
Guido van Rossumab3b0342001-09-18 20:38:53 +0000597 /* If both have the same (non-NULL) tp_compare, use it. */
598 if (f != NULL && f == w->ob_type->tp_compare) {
599 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000600 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000601 }
602
603 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
604 if (f == _PyObject_SlotCompare ||
605 w->ob_type->tp_compare == _PyObject_SlotCompare)
606 return _PyObject_SlotCompare(v, w);
607
Armin Rigoa1748132004-12-23 22:13:13 +0000608 /* If we're here, v and w,
609 a) are not instances;
610 b) have different types or a type without tp_compare; and
611 c) don't have a user-defined tp_compare.
612 tp_compare implementations in C assume that both arguments
613 have their type, so we give up if the coercion fails or if
614 it yields types which are still incompatible (which can
615 happen with a user-defined nb_coerce).
616 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000617 c = PyNumber_CoerceEx(&v, &w);
618 if (c < 0)
619 return -2;
620 if (c > 0)
621 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000622 f = v->ob_type->tp_compare;
623 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000624 c = (*f)(v, w);
625 Py_DECREF(v);
626 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000627 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000628 }
629
Guido van Rossume797ec12001-01-17 15:24:28 +0000630 /* No comparison defined */
631 Py_DECREF(v);
632 Py_DECREF(w);
633 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000634}
635
Guido van Rossume797ec12001-01-17 15:24:28 +0000636/* Final fallback 3-way comparison, returning an int. Return:
637 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000638 -1 if v < w;
639 0 if v == w;
640 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000641*/
642static int
643default_3way_compare(PyObject *v, PyObject *w)
644{
645 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000646 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000647
648 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000649 /* When comparing these pointers, they must be cast to
650 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
651 * uintptr_t). ANSI specifies that pointer compares other
652 * than == and != to non-related structures are undefined.
653 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000654 Py_uintptr_t vv = (Py_uintptr_t)v;
655 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000656 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
657 }
658
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000659#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000660 /* Special case for Unicode */
661 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
662 c = PyUnicode_Compare(v, w);
663 if (!PyErr_Occurred())
664 return c;
665 /* TypeErrors are ignored: if Unicode coercion fails due
666 to one of the arguments not having the right type, we
667 continue as defined by the coercion protocol (see
668 above). Luckily, decoding errors are reported as
669 ValueErrors and are not masked by this technique. */
670 if (!PyErr_ExceptionMatches(PyExc_TypeError))
671 return -2;
672 PyErr_Clear();
673 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000674#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000675
Guido van Rossum0871e932001-01-22 19:28:09 +0000676 /* None is smaller than anything */
677 if (v == Py_None)
678 return -1;
679 if (w == Py_None)
680 return 1;
681
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000682 /* different type: compare type names; numbers are smaller */
683 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000684 vname = "";
685 else
686 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000687 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000688 wname = "";
689 else
690 wname = w->ob_type->tp_name;
691 c = strcmp(vname, wname);
692 if (c < 0)
693 return -1;
694 if (c > 0)
695 return 1;
696 /* Same type name, or (more likely) incomparable numeric types */
697 return ((Py_uintptr_t)(v->ob_type) < (
698 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000699}
700
Tim Peters6d60b2e2001-05-07 20:53:51 +0000701/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000702 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000703 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000704 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000705 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000706 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000707 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000708*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000709static int
Fred Drake100814d2000-07-09 15:48:49 +0000710do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000711{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000712 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000713 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000714
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000715 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000716 && (f = v->ob_type->tp_compare) != NULL) {
717 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000718 if (PyInstance_Check(v)) {
719 /* Instance tp_compare has a different signature.
720 But if it returns undefined we fall through. */
721 if (c != 2)
722 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000723 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000724 }
725 else
726 return adjust_tp_compare(c);
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000727 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000728 /* We only get here if one of the following is true:
729 a) v and w have different types
730 b) v and w have the same type, which doesn't have tp_compare
731 c) v and w are instances, and either __cmp__ is not defined or
732 __cmp__ returns NotImplemented
733 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000734 c = try_rich_to_3way_compare(v, w);
735 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000736 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000737 c = try_3way_compare(v, w);
738 if (c < 2)
739 return c;
740 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000741}
742
Tim Petersc99213f2001-11-04 05:57:16 +0000743/* Compare v to w. Return
744 -1 if v < w or exception (PyErr_Occurred() true in latter case).
745 0 if v == w.
746 1 if v > w.
747 XXX The docs (C API manual) say the return value is undefined in case
748 XXX of error.
749*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000750int
Fred Drake100814d2000-07-09 15:48:49 +0000751PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000752{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000753 int result;
754
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000755 if (v == NULL || w == NULL) {
756 PyErr_BadInternalCall();
757 return -1;
758 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759 if (v == w)
760 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000761 if (Py_EnterRecursiveCall(" in cmp"))
762 return -1;
763 result = do_cmp(v, w);
764 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000765 return result < 0 ? -1 : result;
766}
767
Tim Petersc99213f2001-11-04 05:57:16 +0000768/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000769static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000770convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000771{
Guido van Rossume797ec12001-01-17 15:24:28 +0000772 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000773 switch (op) {
774 case Py_LT: c = c < 0; break;
775 case Py_LE: c = c <= 0; break;
776 case Py_EQ: c = c == 0; break;
777 case Py_NE: c = c != 0; break;
778 case Py_GT: c = c > 0; break;
779 case Py_GE: c = c >= 0; break;
780 }
781 result = c ? Py_True : Py_False;
782 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000783 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000784}
Tim Peters803526b2002-07-07 05:13:56 +0000785
Tim Petersc99213f2001-11-04 05:57:16 +0000786/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
787 Return
788 NULL if error
789 Py_True if v op w
790 Py_False if not (v op w)
791*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000792static PyObject *
793try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
794{
795 int c;
796
797 c = try_3way_compare(v, w);
798 if (c >= 2)
799 c = default_3way_compare(v, w);
800 if (c <= -2)
801 return NULL;
802 return convert_3way_to_object(op, c);
803}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804
Tim Petersc99213f2001-11-04 05:57:16 +0000805/* Do rich comparison on v and w. Return
806 NULL if error
807 Else a new reference to an object other than Py_NotImplemented, usually(?):
808 Py_True if v op w
809 Py_False if not (v op w)
810*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000811static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000812do_richcmp(PyObject *v, PyObject *w, int op)
813{
814 PyObject *res;
815
816 res = try_rich_compare(v, w, op);
817 if (res != Py_NotImplemented)
818 return res;
819 Py_DECREF(res);
820
821 return try_3way_to_rich_compare(v, w, op);
822}
823
Tim Petersc99213f2001-11-04 05:57:16 +0000824/* Return:
825 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000826 some object not equal to NotImplemented if it is implemented
827 (this latter object may not be a Boolean).
828*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000829PyObject *
830PyObject_RichCompare(PyObject *v, PyObject *w, int op)
831{
832 PyObject *res;
833
834 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000835 if (Py_EnterRecursiveCall(" in cmp"))
836 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000837
Armin Rigo2b3eb402003-10-28 12:05:48 +0000838 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000839 get out cheap (don't bother with coercions etc.). */
840 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
841 cmpfunc fcmp;
842 richcmpfunc frich = RICHCOMPARE(v->ob_type);
843 /* If the type has richcmp, try it first. try_rich_compare
844 tries it two-sided, which is not needed since we've a
845 single type only. */
846 if (frich != NULL) {
847 res = (*frich)(v, w, op);
848 if (res != Py_NotImplemented)
849 goto Done;
850 Py_DECREF(res);
851 }
852 /* No richcmp, or this particular richmp not implemented.
853 Try 3-way cmp. */
854 fcmp = v->ob_type->tp_compare;
855 if (fcmp != NULL) {
856 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000857 c = adjust_tp_compare(c);
858 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000859 res = NULL;
860 goto Done;
861 }
862 res = convert_3way_to_object(op, c);
863 goto Done;
864 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000865 }
Tim Peters67754e92001-11-04 07:29:31 +0000866
867 /* Fast path not taken, or couldn't deliver a useful result. */
868 res = do_richcmp(v, w, op);
869Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000870 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000871 return res;
872}
873
Tim Petersde9725f2001-05-05 10:06:17 +0000874/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000875int
876PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
877{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000878 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000879 int ok;
880
Raymond Hettinger93d44812004-03-21 17:01:44 +0000881 /* Quick result when objects are the same.
882 Guarantees that identity implies equality. */
883 if (v == w) {
884 if (op == Py_EQ)
885 return 1;
886 else if (op == Py_NE)
887 return 0;
888 }
889
890 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000891 if (res == NULL)
892 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000893 if (PyBool_Check(res))
894 ok = (res == Py_True);
895 else
896 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000897 Py_DECREF(res);
898 return ok;
899}
Fred Drake13634cf2000-06-29 19:17:04 +0000900
901/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000902 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000903
904 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
905*/
906
907long
Fred Drake100814d2000-07-09 15:48:49 +0000908_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000909{
Tim Peters39dce292000-08-15 03:34:48 +0000910 double intpart, fractpart;
911 int expo;
912 long hipart;
913 long x; /* the final hash value */
914 /* This is designed so that Python numbers of different types
915 * that compare equal hash to the same value; otherwise comparisons
916 * of mapping keys will turn out weird.
917 */
918
Tim Peters39dce292000-08-15 03:34:48 +0000919 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000920 if (fractpart == 0.0) {
921 /* This must return the same hash as an equal int or long. */
922 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
923 /* Convert to long and use its hash. */
924 PyObject *plong; /* converted to Python long */
925 if (Py_IS_INFINITY(intpart))
926 /* can't convert to long int -- arbitrary */
927 v = v < 0 ? -271828.0 : 314159.0;
928 plong = PyLong_FromDouble(v);
929 if (plong == NULL)
930 return -1;
931 x = PyObject_Hash(plong);
932 Py_DECREF(plong);
933 return x;
934 }
935 /* Fits in a C long == a Python int, so is its own hash. */
936 x = (long)intpart;
937 if (x == -1)
938 x = -2;
939 return x;
940 }
941 /* The fractional part is non-zero, so we don't have to worry about
942 * making this match the hash of some other type.
943 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000944 * Since the VAX D double format has 56 mantissa bits, which is the
945 * most of any double format in use, each of these parts may have as
946 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000947 * So, assuming sizeof(long) >= 4, each part can be broken into two
948 * longs; frexp and multiplication are used to do that.
949 * Also, since the Cray double format has 15 exponent bits, which is
950 * the most of any double format in use, shifting the exponent field
951 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000952 */
Tim Peters39dce292000-08-15 03:34:48 +0000953 v = frexp(v, &expo);
954 v *= 2147483648.0; /* 2**31 */
955 hipart = (long)v; /* take the top 32 bits */
956 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
957 x = hipart + (long)v + (expo << 15);
958 if (x == -1)
959 x = -2;
960 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000961}
962
963long
Fred Drake100814d2000-07-09 15:48:49 +0000964_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000965{
966#if SIZEOF_LONG >= SIZEOF_VOID_P
967 return (long)p;
968#else
969 /* convert to a Python long and hash that */
970 PyObject* longobj;
971 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000972
Fred Drake13634cf2000-06-29 19:17:04 +0000973 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
974 x = -1;
975 goto finally;
976 }
977 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000978
Fred Drake13634cf2000-06-29 19:17:04 +0000979finally:
980 Py_XDECREF(longobj);
981 return x;
982#endif
983}
984
985
Guido van Rossum9bfef441993-03-29 10:43:31 +0000986long
Fred Drake100814d2000-07-09 15:48:49 +0000987PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000988{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000990 if (tp->tp_hash != NULL)
991 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000992 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000993 return _Py_HashPointer(v); /* Use address as hash value */
994 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000995 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000996 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000997 return -1;
998}
999
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001000PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001001PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001002{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001004
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001006 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 w = PyString_InternFromString(name);
1008 if (w == NULL)
1009 return NULL;
1010 res = PyObject_GetAttr(v, w);
1011 Py_XDECREF(w);
1012 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001013}
1014
1015int
Fred Drake100814d2000-07-09 15:48:49 +00001016PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001017{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001018 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001019 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001020 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001021 return 1;
1022 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001023 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001024 return 0;
1025}
1026
1027int
Fred Drake100814d2000-07-09 15:48:49 +00001028PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001029{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030 PyObject *s;
1031 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001032
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001034 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001035 s = PyString_InternFromString(name);
1036 if (s == NULL)
1037 return -1;
1038 res = PyObject_SetAttr(v, s, w);
1039 Py_XDECREF(s);
1040 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001041}
1042
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001043PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001044PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001045{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046 PyTypeObject *tp = v->ob_type;
1047
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001048 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001049#ifdef Py_USING_UNICODE
1050 /* The Unicode to string conversion is done here because the
1051 existing tp_getattro slots expect a string object as name
1052 and we wouldn't want to break those. */
1053 if (PyUnicode_Check(name)) {
1054 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1055 if (name == NULL)
1056 return NULL;
1057 }
1058 else
1059#endif
1060 {
1061 PyErr_SetString(PyExc_TypeError,
1062 "attribute name must be string");
1063 return NULL;
1064 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001065 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001066 if (tp->tp_getattro != NULL)
1067 return (*tp->tp_getattro)(v, name);
1068 if (tp->tp_getattr != NULL)
1069 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1070 PyErr_Format(PyExc_AttributeError,
1071 "'%.50s' object has no attribute '%.400s'",
1072 tp->tp_name, PyString_AS_STRING(name));
1073 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001074}
1075
1076int
Fred Drake100814d2000-07-09 15:48:49 +00001077PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001078{
1079 PyObject *res = PyObject_GetAttr(v, name);
1080 if (res != NULL) {
1081 Py_DECREF(res);
1082 return 1;
1083 }
1084 PyErr_Clear();
1085 return 0;
1086}
1087
1088int
Fred Drake100814d2000-07-09 15:48:49 +00001089PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001090{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001092 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001093
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001094 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001095#ifdef Py_USING_UNICODE
1096 /* The Unicode to string conversion is done here because the
1097 existing tp_setattro slots expect a string object as name
1098 and we wouldn't want to break those. */
1099 if (PyUnicode_Check(name)) {
1100 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1101 if (name == NULL)
1102 return -1;
1103 }
Tim Peters803526b2002-07-07 05:13:56 +00001104 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001105#endif
1106 {
1107 PyErr_SetString(PyExc_TypeError,
1108 "attribute name must be string");
1109 return -1;
1110 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001111 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 else
1113 Py_INCREF(name);
1114
1115 PyString_InternInPlace(&name);
1116 if (tp->tp_setattro != NULL) {
1117 err = (*tp->tp_setattro)(v, name, value);
1118 Py_DECREF(name);
1119 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001120 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 if (tp->tp_setattr != NULL) {
1122 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1123 Py_DECREF(name);
1124 return err;
1125 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001126 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001127 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1128 PyErr_Format(PyExc_TypeError,
1129 "'%.100s' object has no attributes "
1130 "(%s .%.100s)",
1131 tp->tp_name,
1132 value==NULL ? "del" : "assign to",
1133 PyString_AS_STRING(name));
1134 else
1135 PyErr_Format(PyExc_TypeError,
1136 "'%.100s' object has only read-only attributes "
1137 "(%s .%.100s)",
1138 tp->tp_name,
1139 value==NULL ? "del" : "assign to",
1140 PyString_AS_STRING(name));
1141 return -1;
1142}
1143
1144/* Helper to get a pointer to an object's __dict__ slot, if any */
1145
1146PyObject **
1147_PyObject_GetDictPtr(PyObject *obj)
1148{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001149 long dictoffset;
1150 PyTypeObject *tp = obj->ob_type;
1151
1152 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1153 return NULL;
1154 dictoffset = tp->tp_dictoffset;
1155 if (dictoffset == 0)
1156 return NULL;
1157 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001158 int tsize;
1159 size_t size;
1160
1161 tsize = ((PyVarObject *)obj)->ob_size;
1162 if (tsize < 0)
1163 tsize = -tsize;
1164 size = _PyObject_VAR_SIZE(tp, tsize);
1165
Tim Peters6d483d32001-10-06 21:27:34 +00001166 dictoffset += (long)size;
1167 assert(dictoffset > 0);
1168 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001169 }
1170 return (PyObject **) ((char *)obj + dictoffset);
1171}
1172
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001174PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001175{
1176 Py_INCREF(obj);
1177 return obj;
1178}
1179
Michael W. Hudson1593f502004-09-14 17:09:47 +00001180/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1181
Raymond Hettinger01538262003-03-17 08:24:35 +00001182PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1184{
1185 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001186 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001187 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001188 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001189 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001190 PyObject **dictptr;
1191
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001192 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001193#ifdef Py_USING_UNICODE
1194 /* The Unicode to string conversion is done here because the
1195 existing tp_setattro slots expect a string object as name
1196 and we wouldn't want to break those. */
1197 if (PyUnicode_Check(name)) {
1198 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1199 if (name == NULL)
1200 return NULL;
1201 }
Tim Peters803526b2002-07-07 05:13:56 +00001202 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001203#endif
1204 {
1205 PyErr_SetString(PyExc_TypeError,
1206 "attribute name must be string");
1207 return NULL;
1208 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001209 }
1210 else
1211 Py_INCREF(name);
1212
Tim Peters6d6c1a32001-08-02 04:15:00 +00001213 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001214 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001215 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216 }
1217
Guido van Rossum056fbf42002-08-19 19:22:50 +00001218 /* Inline _PyType_Lookup */
1219 {
1220 int i, n;
1221 PyObject *mro, *base, *dict;
1222
1223 /* Look in tp_dict of types in MRO */
1224 mro = tp->tp_mro;
1225 assert(mro != NULL);
1226 assert(PyTuple_Check(mro));
1227 n = PyTuple_GET_SIZE(mro);
1228 for (i = 0; i < n; i++) {
1229 base = PyTuple_GET_ITEM(mro, i);
1230 if (PyClass_Check(base))
1231 dict = ((PyClassObject *)base)->cl_dict;
1232 else {
1233 assert(PyType_Check(base));
1234 dict = ((PyTypeObject *)base)->tp_dict;
1235 }
1236 assert(dict && PyDict_Check(dict));
1237 descr = PyDict_GetItem(dict, name);
1238 if (descr != NULL)
1239 break;
1240 }
1241 }
1242
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001243 Py_XINCREF(descr);
1244
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001246 if (descr != NULL &&
1247 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001248 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001249 if (f != NULL && PyDescr_IsData(descr)) {
1250 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001251 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001252 goto done;
1253 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001254 }
1255
Guido van Rossumc66ff442002-08-19 16:50:48 +00001256 /* Inline _PyObject_GetDictPtr */
1257 dictoffset = tp->tp_dictoffset;
1258 if (dictoffset != 0) {
1259 PyObject *dict;
1260 if (dictoffset < 0) {
1261 int tsize;
1262 size_t size;
1263
1264 tsize = ((PyVarObject *)obj)->ob_size;
1265 if (tsize < 0)
1266 tsize = -tsize;
1267 size = _PyObject_VAR_SIZE(tp, tsize);
1268
1269 dictoffset += (long)size;
1270 assert(dictoffset > 0);
1271 assert(dictoffset % SIZEOF_VOID_P == 0);
1272 }
1273 dictptr = (PyObject **) ((char *)obj + dictoffset);
1274 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001275 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001276 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277 if (res != NULL) {
1278 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001279 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001280 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001281 }
1282 }
1283 }
1284
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001285 if (f != NULL) {
1286 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001287 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001288 goto done;
1289 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290
1291 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001292 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001293 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001294 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001295 }
1296
1297 PyErr_Format(PyExc_AttributeError,
1298 "'%.50s' object has no attribute '%.400s'",
1299 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001300 done:
1301 Py_DECREF(name);
1302 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303}
1304
1305int
1306PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1307{
1308 PyTypeObject *tp = obj->ob_type;
1309 PyObject *descr;
1310 descrsetfunc f;
1311 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001312 int res = -1;
1313
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001314 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001315#ifdef Py_USING_UNICODE
1316 /* The Unicode to string conversion is done here because the
1317 existing tp_setattro slots expect a string object as name
1318 and we wouldn't want to break those. */
1319 if (PyUnicode_Check(name)) {
1320 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1321 if (name == NULL)
1322 return -1;
1323 }
Tim Peters803526b2002-07-07 05:13:56 +00001324 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001325#endif
1326 {
1327 PyErr_SetString(PyExc_TypeError,
1328 "attribute name must be string");
1329 return -1;
1330 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001331 }
1332 else
1333 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334
1335 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001336 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001337 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338 }
1339
1340 descr = _PyType_Lookup(tp, name);
1341 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001342 if (descr != NULL &&
1343 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001344 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001345 if (f != NULL && PyDescr_IsData(descr)) {
1346 res = f(descr, obj, value);
1347 goto done;
1348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001349 }
1350
1351 dictptr = _PyObject_GetDictPtr(obj);
1352 if (dictptr != NULL) {
1353 PyObject *dict = *dictptr;
1354 if (dict == NULL && value != NULL) {
1355 dict = PyDict_New();
1356 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001357 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358 *dictptr = dict;
1359 }
1360 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001361 if (value == NULL)
1362 res = PyDict_DelItem(dict, name);
1363 else
1364 res = PyDict_SetItem(dict, name, value);
1365 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1366 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001367 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368 }
1369 }
1370
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001371 if (f != NULL) {
1372 res = f(descr, obj, value);
1373 goto done;
1374 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375
1376 if (descr == NULL) {
1377 PyErr_Format(PyExc_AttributeError,
1378 "'%.50s' object has no attribute '%.400s'",
1379 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001380 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001381 }
1382
1383 PyErr_Format(PyExc_AttributeError,
1384 "'%.50s' object attribute '%.400s' is read-only",
1385 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001386 done:
1387 Py_DECREF(name);
1388 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001389}
1390
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001391/* Test a value used as condition, e.g., in a for or if statement.
1392 Return -1 if an error occurred */
1393
1394int
Fred Drake100814d2000-07-09 15:48:49 +00001395PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001396{
1397 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001398 if (v == Py_True)
1399 return 1;
1400 if (v == Py_False)
1401 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001402 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001403 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001404 else if (v->ob_type->tp_as_number != NULL &&
1405 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001406 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001407 else if (v->ob_type->tp_as_mapping != NULL &&
1408 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001409 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001410 else if (v->ob_type->tp_as_sequence != NULL &&
1411 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001412 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1413 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001414 return 1;
1415 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001416}
1417
Tim Peters803526b2002-07-07 05:13:56 +00001418/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001419 Return -1 if an error occurred */
1420
1421int
Fred Drake100814d2000-07-09 15:48:49 +00001422PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001423{
1424 int res;
1425 res = PyObject_IsTrue(v);
1426 if (res < 0)
1427 return res;
1428 return res == 0;
1429}
1430
Guido van Rossum5524a591995-01-10 15:26:20 +00001431/* Coerce two numeric types to the "larger" one.
1432 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001433 Return value:
1434 -1 if an error occurred;
1435 0 if the coercion succeeded (and then the reference counts are increased);
1436 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001437*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001438int
Fred Drake100814d2000-07-09 15:48:49 +00001439PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001440{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441 register PyObject *v = *pv;
1442 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001443 int res;
1444
Guido van Rossum517c7d42002-04-26 02:49:14 +00001445 /* Shortcut only for old-style types */
1446 if (v->ob_type == w->ob_type &&
1447 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1448 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001449 Py_INCREF(v);
1450 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001451 return 0;
1452 }
1453 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1454 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1455 if (res <= 0)
1456 return res;
1457 }
1458 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1459 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1460 if (res <= 0)
1461 return res;
1462 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001463 return 1;
1464}
1465
Guido van Rossume797ec12001-01-17 15:24:28 +00001466/* Coerce two numeric types to the "larger" one.
1467 Increment the reference count on each argument.
1468 Return -1 and raise an exception if no coercion is possible
1469 (and then no reference count is incremented).
1470*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001471int
Fred Drake100814d2000-07-09 15:48:49 +00001472PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001473{
1474 int err = PyNumber_CoerceEx(pv, pw);
1475 if (err <= 0)
1476 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001477 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001478 return -1;
1479}
1480
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001481
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001482/* Test whether an object can be called */
1483
1484int
Fred Drake100814d2000-07-09 15:48:49 +00001485PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001486{
1487 if (x == NULL)
1488 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001489 if (PyInstance_Check(x)) {
1490 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001491 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001492 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001493 return 0;
1494 }
1495 /* Could test recursively but don't, for fear of endless
1496 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001497 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001498 return 1;
1499 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001500 else {
1501 return x->ob_type->tp_call != NULL;
1502 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001503}
1504
Tim Peters7eea37e2001-09-04 22:08:56 +00001505/* Helper for PyObject_Dir.
1506 Merge the __dict__ of aclass into dict, and recursively also all
1507 the __dict__s of aclass's base classes. The order of merging isn't
1508 defined, as it's expected that only the final set of dict keys is
1509 interesting.
1510 Return 0 on success, -1 on error.
1511*/
1512
1513static int
1514merge_class_dict(PyObject* dict, PyObject* aclass)
1515{
1516 PyObject *classdict;
1517 PyObject *bases;
1518
1519 assert(PyDict_Check(dict));
1520 assert(aclass);
1521
1522 /* Merge in the type's dict (if any). */
1523 classdict = PyObject_GetAttrString(aclass, "__dict__");
1524 if (classdict == NULL)
1525 PyErr_Clear();
1526 else {
1527 int status = PyDict_Update(dict, classdict);
1528 Py_DECREF(classdict);
1529 if (status < 0)
1530 return -1;
1531 }
1532
1533 /* Recursively merge in the base types' (if any) dicts. */
1534 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001535 if (bases == NULL)
1536 PyErr_Clear();
1537 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001538 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001539 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001540 n = PySequence_Size(bases); /* This better be right */
1541 if (n < 0)
1542 PyErr_Clear();
1543 else {
1544 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001545 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001546 PyObject *base = PySequence_GetItem(bases, i);
1547 if (base == NULL) {
1548 Py_DECREF(bases);
1549 return -1;
1550 }
Tim Peters18e70832003-02-05 19:35:19 +00001551 status = merge_class_dict(dict, base);
1552 Py_DECREF(base);
1553 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001554 Py_DECREF(bases);
1555 return -1;
1556 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001557 }
1558 }
1559 Py_DECREF(bases);
1560 }
1561 return 0;
1562}
1563
Tim Peters305b5852001-09-17 02:38:46 +00001564/* Helper for PyObject_Dir.
1565 If obj has an attr named attrname that's a list, merge its string
1566 elements into keys of dict.
1567 Return 0 on success, -1 on error. Errors due to not finding the attr,
1568 or the attr not being a list, are suppressed.
1569*/
1570
1571static int
1572merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1573{
1574 PyObject *list;
1575 int result = 0;
1576
1577 assert(PyDict_Check(dict));
1578 assert(obj);
1579 assert(attrname);
1580
1581 list = PyObject_GetAttrString(obj, attrname);
1582 if (list == NULL)
1583 PyErr_Clear();
1584
1585 else if (PyList_Check(list)) {
1586 int i;
1587 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1588 PyObject *item = PyList_GET_ITEM(list, i);
1589 if (PyString_Check(item)) {
1590 result = PyDict_SetItem(dict, item, Py_None);
1591 if (result < 0)
1592 break;
1593 }
1594 }
1595 }
1596
1597 Py_XDECREF(list);
1598 return result;
1599}
1600
Tim Peters7eea37e2001-09-04 22:08:56 +00001601/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1602 docstring, which should be kept in synch with this implementation. */
1603
1604PyObject *
1605PyObject_Dir(PyObject *arg)
1606{
1607 /* Set exactly one of these non-NULL before the end. */
1608 PyObject *result = NULL; /* result list */
1609 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1610
1611 /* If NULL arg, return the locals. */
1612 if (arg == NULL) {
1613 PyObject *locals = PyEval_GetLocals();
1614 if (locals == NULL)
1615 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001616 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001617 if (result == NULL)
1618 goto error;
1619 }
1620
1621 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001622 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001623 masterdict = PyObject_GetAttrString(arg, "__dict__");
1624 if (masterdict == NULL)
1625 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001626 if (!PyDict_Check(masterdict)) {
1627 PyErr_SetString(PyExc_TypeError,
1628 "module.__dict__ is not a dictionary");
1629 goto error;
1630 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001631 }
1632
1633 /* Elif some form of type or class, grab its dict and its bases.
1634 We deliberately don't suck up its __class__, as methods belonging
1635 to the metaclass would probably be more confusing than helpful. */
1636 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1637 masterdict = PyDict_New();
1638 if (masterdict == NULL)
1639 goto error;
1640 if (merge_class_dict(masterdict, arg) < 0)
1641 goto error;
1642 }
1643
1644 /* Else look at its dict, and the attrs reachable from its class. */
1645 else {
1646 PyObject *itsclass;
1647 /* Create a dict to start with. CAUTION: Not everything
1648 responding to __dict__ returns a dict! */
1649 masterdict = PyObject_GetAttrString(arg, "__dict__");
1650 if (masterdict == NULL) {
1651 PyErr_Clear();
1652 masterdict = PyDict_New();
1653 }
1654 else if (!PyDict_Check(masterdict)) {
1655 Py_DECREF(masterdict);
1656 masterdict = PyDict_New();
1657 }
1658 else {
1659 /* The object may have returned a reference to its
1660 dict, so copy it to avoid mutating it. */
1661 PyObject *temp = PyDict_Copy(masterdict);
1662 Py_DECREF(masterdict);
1663 masterdict = temp;
1664 }
1665 if (masterdict == NULL)
1666 goto error;
1667
Tim Peters305b5852001-09-17 02:38:46 +00001668 /* Merge in __members__ and __methods__ (if any).
1669 XXX Would like this to go away someday; for now, it's
1670 XXX needed to get at im_self etc of method objects. */
1671 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1672 goto error;
1673 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1674 goto error;
1675
Tim Peters7eea37e2001-09-04 22:08:56 +00001676 /* Merge in attrs reachable from its class.
1677 CAUTION: Not all objects have a __class__ attr. */
1678 itsclass = PyObject_GetAttrString(arg, "__class__");
1679 if (itsclass == NULL)
1680 PyErr_Clear();
1681 else {
1682 int status = merge_class_dict(masterdict, itsclass);
1683 Py_DECREF(itsclass);
1684 if (status < 0)
1685 goto error;
1686 }
1687 }
1688
1689 assert((result == NULL) ^ (masterdict == NULL));
1690 if (masterdict != NULL) {
1691 /* The result comes from its keys. */
1692 assert(result == NULL);
1693 result = PyDict_Keys(masterdict);
1694 if (result == NULL)
1695 goto error;
1696 }
1697
1698 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001699 if (!PyList_Check(result)) {
Tim Petersf4aca752004-09-23 02:39:37 +00001700 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001701 "Expected keys() to be a list.");
1702 goto error;
1703 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001704 if (PyList_Sort(result) != 0)
1705 goto error;
1706 else
1707 goto normal_return;
1708
1709 error:
1710 Py_XDECREF(result);
1711 result = NULL;
1712 /* fall through */
1713 normal_return:
1714 Py_XDECREF(masterdict);
1715 return result;
1716}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001717
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001718/*
1719NoObject is usable as a non-NULL undefined value, used by the macro None.
1720There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001721so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001722(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001723*/
1724
Guido van Rossum0c182a11992-03-27 17:26:13 +00001725/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001726static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001727none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001728{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001729 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001730}
1731
Barry Warsaw9bf16442001-01-23 16:24:35 +00001732/* ARGUSED */
1733static void
Tim Peters803526b2002-07-07 05:13:56 +00001734none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001735{
1736 /* This should never get called, but we also don't want to SEGV if
1737 * we accidently decref None out of existance.
1738 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001739 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001740}
1741
1742
Guido van Rossumba21a492001-08-16 08:17:26 +00001743static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001744 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001745 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001746 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001747 0,
1748 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001749 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001750 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001751 0, /*tp_getattr*/
1752 0, /*tp_setattr*/
1753 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001754 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001755 0, /*tp_as_number*/
1756 0, /*tp_as_sequence*/
1757 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001758 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001759};
1760
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001761PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001762 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001763};
1764
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001765/* NotImplemented is an object that can be used to signal that an
1766 operation is not implemented for the given type combination. */
1767
1768static PyObject *
1769NotImplemented_repr(PyObject *op)
1770{
1771 return PyString_FromString("NotImplemented");
1772}
1773
1774static PyTypeObject PyNotImplemented_Type = {
1775 PyObject_HEAD_INIT(&PyType_Type)
1776 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001777 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001778 0,
1779 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001780 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001781 0, /*tp_print*/
1782 0, /*tp_getattr*/
1783 0, /*tp_setattr*/
1784 0, /*tp_compare*/
1785 (reprfunc)NotImplemented_repr, /*tp_repr*/
1786 0, /*tp_as_number*/
1787 0, /*tp_as_sequence*/
1788 0, /*tp_as_mapping*/
1789 0, /*tp_hash */
1790};
1791
1792PyObject _Py_NotImplementedStruct = {
1793 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1794};
1795
Guido van Rossumba21a492001-08-16 08:17:26 +00001796void
1797_Py_ReadyTypes(void)
1798{
1799 if (PyType_Ready(&PyType_Type) < 0)
1800 Py_FatalError("Can't initialize 'type'");
1801
Fred Drake0a4dd392004-07-02 18:57:45 +00001802 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1803 Py_FatalError("Can't initialize 'weakref'");
1804
Guido van Rossum77f6a652002-04-03 22:41:51 +00001805 if (PyType_Ready(&PyBool_Type) < 0)
1806 Py_FatalError("Can't initialize 'bool'");
1807
Guido van Rossumcacfc072002-05-24 19:01:59 +00001808 if (PyType_Ready(&PyString_Type) < 0)
1809 Py_FatalError("Can't initialize 'str'");
1810
Guido van Rossumba21a492001-08-16 08:17:26 +00001811 if (PyType_Ready(&PyList_Type) < 0)
1812 Py_FatalError("Can't initialize 'list'");
1813
1814 if (PyType_Ready(&PyNone_Type) < 0)
1815 Py_FatalError("Can't initialize type(None)");
1816
1817 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1818 Py_FatalError("Can't initialize type(NotImplemented)");
1819}
1820
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001821
Guido van Rossum84a90321996-05-22 16:34:47 +00001822#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001823
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001824void
Fred Drake100814d2000-07-09 15:48:49 +00001825_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001826{
Tim Peters34592512002-07-11 06:23:50 +00001827 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001828 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001829 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001830 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001831}
1832
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001833void
Fred Drake100814d2000-07-09 15:48:49 +00001834_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001835{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001836#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001837 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001838#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001839 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001840 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001841 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001842 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001843 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001844#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001845 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1846 if (p == op)
1847 break;
1848 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001849 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001851#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001852 op->_ob_next->_ob_prev = op->_ob_prev;
1853 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001854 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001855 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001856}
1857
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001858void
Fred Drake100814d2000-07-09 15:48:49 +00001859_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001860{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001861 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001862 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001863 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001864}
1865
Tim Peters269b2a62003-04-17 19:52:29 +00001866/* Print all live objects. Because PyObject_Print is called, the
1867 * interpreter must be in a healthy state.
1868 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001869void
Fred Drake100814d2000-07-09 15:48:49 +00001870_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001871{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001872 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001873 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001874 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001875 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876 if (PyObject_Print(op, fp, 0) != 0)
1877 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001878 putc('\n', fp);
1879 }
1880}
1881
Tim Peters269b2a62003-04-17 19:52:29 +00001882/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1883 * doesn't make any calls to the Python C API, so is always safe to call.
1884 */
1885void
1886_Py_PrintReferenceAddresses(FILE *fp)
1887{
1888 PyObject *op;
1889 fprintf(fp, "Remaining object addresses:\n");
1890 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001891 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1892 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001893}
1894
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001895PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001896_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001897{
1898 int i, n;
1899 PyObject *t = NULL;
1900 PyObject *res, *op;
1901
1902 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1903 return NULL;
1904 op = refchain._ob_next;
1905 res = PyList_New(0);
1906 if (res == NULL)
1907 return NULL;
1908 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1909 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001910 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001911 op = op->_ob_next;
1912 if (op == &refchain)
1913 return res;
1914 }
1915 if (PyList_Append(res, op) < 0) {
1916 Py_DECREF(res);
1917 return NULL;
1918 }
1919 op = op->_ob_next;
1920 }
1921 return res;
1922}
1923
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001924#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001925
1926
1927/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001928PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001929
1930
1931/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001932int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001933
1934
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001935/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001936
Thomas Wouters334fb892000-07-25 12:56:38 +00001937void *
Fred Drake100814d2000-07-09 15:48:49 +00001938PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001939{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001940 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001941}
1942
Thomas Wouters334fb892000-07-25 12:56:38 +00001943void *
1944PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001945{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001946 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001947}
1948
1949void
Thomas Wouters334fb892000-07-25 12:56:38 +00001950PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001951{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001952 PyMem_FREE(p);
1953}
1954
1955
Guido van Rossum86610361998-04-10 22:32:46 +00001956/* These methods are used to control infinite recursion in repr, str, print,
1957 etc. Container objects that may recursively contain themselves,
1958 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1959 Py_ReprLeave() to avoid infinite recursion.
1960
1961 Py_ReprEnter() returns 0 the first time it is called for a particular
1962 object and 1 every time thereafter. It returns -1 if an exception
1963 occurred. Py_ReprLeave() has no return value.
1964
1965 See dictobject.c and listobject.c for examples of use.
1966*/
1967
1968#define KEY "Py_Repr"
1969
1970int
Fred Drake100814d2000-07-09 15:48:49 +00001971Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001972{
1973 PyObject *dict;
1974 PyObject *list;
1975 int i;
1976
1977 dict = PyThreadState_GetDict();
1978 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001979 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001980 list = PyDict_GetItemString(dict, KEY);
1981 if (list == NULL) {
1982 list = PyList_New(0);
1983 if (list == NULL)
1984 return -1;
1985 if (PyDict_SetItemString(dict, KEY, list) < 0)
1986 return -1;
1987 Py_DECREF(list);
1988 }
1989 i = PyList_GET_SIZE(list);
1990 while (--i >= 0) {
1991 if (PyList_GET_ITEM(list, i) == obj)
1992 return 1;
1993 }
1994 PyList_Append(list, obj);
1995 return 0;
1996}
1997
1998void
Fred Drake100814d2000-07-09 15:48:49 +00001999Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002000{
2001 PyObject *dict;
2002 PyObject *list;
2003 int i;
2004
2005 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002006 if (dict == NULL)
2007 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002008 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002009 if (list == NULL || !PyList_Check(list))
2010 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002011 i = PyList_GET_SIZE(list);
2012 /* Count backwards because we always expect obj to be list[-1] */
2013 while (--i >= 0) {
2014 if (PyList_GET_ITEM(list, i) == obj) {
2015 PyList_SetSlice(list, i, i + 1, NULL);
2016 break;
2017 }
2018 }
2019}
Guido van Rossumd724b232000-03-13 16:01:29 +00002020
Tim Peters803526b2002-07-07 05:13:56 +00002021/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002022
Tim Peters803526b2002-07-07 05:13:56 +00002023/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002024int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002025
Tim Peters803526b2002-07-07 05:13:56 +00002026/* List of objects that still need to be cleaned up, singly linked via their
2027 * gc headers' gc_prev pointers.
2028 */
2029PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002030
Tim Peters803526b2002-07-07 05:13:56 +00002031/* Add op to the _PyTrash_delete_later list. Called when the current
2032 * call-stack depth gets large. op must be a currently untracked gc'ed
2033 * object, with refcount 0. Py_DECREF must already have been called on it.
2034 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002035void
Fred Drake100814d2000-07-09 15:48:49 +00002036_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002037{
Tim Peters803526b2002-07-07 05:13:56 +00002038 assert(PyObject_IS_GC(op));
2039 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2040 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002041 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002042 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002043}
2044
Tim Peters803526b2002-07-07 05:13:56 +00002045/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2046 * the call-stack unwinds again.
2047 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002048void
Fred Drake100814d2000-07-09 15:48:49 +00002049_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002050{
2051 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002052 PyObject *op = _PyTrash_delete_later;
2053 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002054
Neil Schemenauerf589c052002-03-29 03:05:54 +00002055 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002056 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002057
Tim Peters803526b2002-07-07 05:13:56 +00002058 /* Call the deallocator directly. This used to try to
2059 * fool Py_DECREF into calling it indirectly, but
2060 * Py_DECREF was already called on this object, and in
2061 * assorted non-release builds calling Py_DECREF again ends
2062 * up distorting allocation statistics.
2063 */
2064 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002065 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002066 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002067 --_PyTrash_delete_nesting;
2068 }
2069}