blob: d86d74f6d7659c14fcdd7eea0506156fc6fc6e17 [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;
Tim Peters803526b2002-07-07 05:13:56 +0000376
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000377 if (v == NULL)
378 res = PyString_FromString("<NULL>");
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000379 if (PyUnicode_CheckExact(v)) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000380 Py_INCREF(v);
381 return v;
382 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000383 if (PyUnicode_Check(v)) {
384 /* For a Unicode subtype that's not a Unicode object,
385 return a true Unicode object with the same data. */
386 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
387 PyUnicode_GET_SIZE(v));
388 }
389 if (PyString_Check(v)) {
Marc-André Lemburgae605342001-03-25 19:16:13 +0000390 Py_INCREF(v);
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000391 res = v;
Marc-André Lemburgae605342001-03-25 19:16:13 +0000392 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000393 else {
394 PyObject *func;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000395 static PyObject *unicodestr;
396 /* XXX As soon as we have a tp_unicode slot, we should
397 check this before trying the __unicode__
398 method. */
399 if (unicodestr == NULL) {
400 unicodestr= PyString_InternFromString(
401 "__unicode__");
402 if (unicodestr == NULL)
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000403 return NULL;
404 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000405 func = PyObject_GetAttr(v, unicodestr);
406 if (func != NULL) {
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000407 res = PyEval_CallObject(func, (PyObject *)NULL);
408 Py_DECREF(func);
409 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000410 else {
411 PyErr_Clear();
412 if (v->ob_type->tp_str != NULL)
413 res = (*v->ob_type->tp_str)(v);
414 else
415 res = PyObject_Repr(v);
416 }
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000417 }
418 if (res == NULL)
419 return NULL;
420 if (!PyUnicode_Check(res)) {
Guido van Rossumb8c65bc2001-10-19 02:01:31 +0000421 PyObject *str;
422 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000423 Py_DECREF(res);
424 if (str)
425 res = str;
426 else
427 return NULL;
428 }
429 return res;
430}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000431#endif
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000432
433
Guido van Rossuma4073002002-05-31 20:03:54 +0000434/* Helper to warn about deprecated tp_compare return values. Return:
435 -2 for an exception;
436 -1 if v < w;
437 0 if v == w;
438 1 if v > w.
439 (This function cannot return 2.)
440*/
441static int
442adjust_tp_compare(int c)
443{
444 if (PyErr_Occurred()) {
445 if (c != -1 && c != -2) {
446 PyObject *t, *v, *tb;
447 PyErr_Fetch(&t, &v, &tb);
448 if (PyErr_Warn(PyExc_RuntimeWarning,
449 "tp_compare didn't return -1 or -2 "
450 "for exception") < 0) {
451 Py_XDECREF(t);
452 Py_XDECREF(v);
453 Py_XDECREF(tb);
454 }
455 else
456 PyErr_Restore(t, v, tb);
457 }
458 return -2;
459 }
460 else if (c < -1 || c > 1) {
461 if (PyErr_Warn(PyExc_RuntimeWarning,
462 "tp_compare didn't return -1, 0 or 1") < 0)
463 return -2;
464 else
465 return c < -1 ? -1 : 1;
466 }
467 else {
468 assert(c >= -1 && c <= 1);
469 return c;
470 }
471}
472
473
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000474/* Macro to get the tp_richcompare field of a type if defined */
475#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
476 ? (t)->tp_richcompare : NULL)
477
Guido van Rossume797ec12001-01-17 15:24:28 +0000478/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000479int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000480
Guido van Rossume797ec12001-01-17 15:24:28 +0000481/* Try a genuine rich comparison, returning an object. Return:
482 NULL for exception;
483 NotImplemented if this particular rich comparison is not implemented or
484 undefined;
485 some object not equal to NotImplemented if it is implemented
486 (this latter object may not be a Boolean).
487*/
488static PyObject *
489try_rich_compare(PyObject *v, PyObject *w, int op)
490{
491 richcmpfunc f;
492 PyObject *res;
493
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000494 if (v->ob_type != w->ob_type &&
495 PyType_IsSubtype(w->ob_type, v->ob_type) &&
496 (f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000497 res = (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000498 if (res != Py_NotImplemented)
499 return res;
500 Py_DECREF(res);
501 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000502 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000503 res = (*f)(v, w, op);
504 if (res != Py_NotImplemented)
505 return res;
506 Py_DECREF(res);
507 }
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000508 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
Tim Petersf4aca752004-09-23 02:39:37 +0000509 return (*f)(w, v, _Py_SwappedOp[op]);
Guido van Rossume797ec12001-01-17 15:24:28 +0000510 }
511 res = Py_NotImplemented;
512 Py_INCREF(res);
513 return res;
514}
515
516/* Try a genuine rich comparison, returning an int. Return:
517 -1 for exception (including the case where try_rich_compare() returns an
518 object that's not a Boolean);
Tim Petersc99213f2001-11-04 05:57:16 +0000519 0 if the outcome is false;
520 1 if the outcome is true;
521 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000522*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000523static int
Guido van Rossume797ec12001-01-17 15:24:28 +0000524try_rich_compare_bool(PyObject *v, PyObject *w, int op)
525{
526 PyObject *res;
527 int ok;
528
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000529 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000530 return 2; /* Shortcut, avoid INCREF+DECREF */
531 res = try_rich_compare(v, w, op);
532 if (res == NULL)
533 return -1;
534 if (res == Py_NotImplemented) {
535 Py_DECREF(res);
536 return 2;
537 }
538 ok = PyObject_IsTrue(res);
539 Py_DECREF(res);
540 return ok;
541}
542
543/* Try rich comparisons to determine a 3-way comparison. Return:
544 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000545 -1 if v < w;
546 0 if v == w;
547 1 if v > w;
548 2 if this particular rich comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000549*/
550static int
551try_rich_to_3way_compare(PyObject *v, PyObject *w)
552{
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000553 static struct { int op; int outcome; } tries[3] = {
554 /* Try this operator, and if it is true, use this outcome: */
555 {Py_EQ, 0},
556 {Py_LT, -1},
557 {Py_GT, 1},
558 };
559 int i;
560
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000561 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
Guido van Rossume797ec12001-01-17 15:24:28 +0000562 return 2; /* Shortcut */
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000563
564 for (i = 0; i < 3; i++) {
565 switch (try_rich_compare_bool(v, w, tries[i].op)) {
566 case -1:
Tim Peters6d60b2e2001-05-07 20:53:51 +0000567 return -2;
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000568 case 1:
569 return tries[i].outcome;
570 }
Guido van Rossume797ec12001-01-17 15:24:28 +0000571 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000572
573 return 2;
Guido van Rossume797ec12001-01-17 15:24:28 +0000574}
575
576/* Try a 3-way comparison, returning an int. Return:
577 -2 for an exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000578 -1 if v < w;
579 0 if v == w;
580 1 if v > w;
581 2 if this particular 3-way comparison is not implemented or undefined.
Guido van Rossume797ec12001-01-17 15:24:28 +0000582*/
583static int
584try_3way_compare(PyObject *v, PyObject *w)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000585{
586 int c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000587 cmpfunc f;
588
589 /* Comparisons involving instances are given to instance_compare,
590 which has the same return conventions as this function. */
591
Guido van Rossumab3b0342001-09-18 20:38:53 +0000592 f = v->ob_type->tp_compare;
Guido van Rossume797ec12001-01-17 15:24:28 +0000593 if (PyInstance_Check(v))
Guido van Rossumab3b0342001-09-18 20:38:53 +0000594 return (*f)(v, w);
Guido van Rossume797ec12001-01-17 15:24:28 +0000595 if (PyInstance_Check(w))
596 return (*w->ob_type->tp_compare)(v, w);
597
Guido van Rossumab3b0342001-09-18 20:38:53 +0000598 /* If both have the same (non-NULL) tp_compare, use it. */
599 if (f != NULL && f == w->ob_type->tp_compare) {
600 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000601 return adjust_tp_compare(c);
Guido van Rossumab3b0342001-09-18 20:38:53 +0000602 }
603
604 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
605 if (f == _PyObject_SlotCompare ||
606 w->ob_type->tp_compare == _PyObject_SlotCompare)
607 return _PyObject_SlotCompare(v, w);
608
Armin Rigoa1748132004-12-23 22:13:13 +0000609 /* If we're here, v and w,
610 a) are not instances;
611 b) have different types or a type without tp_compare; and
612 c) don't have a user-defined tp_compare.
613 tp_compare implementations in C assume that both arguments
614 have their type, so we give up if the coercion fails or if
615 it yields types which are still incompatible (which can
616 happen with a user-defined nb_coerce).
617 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000618 c = PyNumber_CoerceEx(&v, &w);
619 if (c < 0)
620 return -2;
621 if (c > 0)
622 return 2;
Armin Rigoa1748132004-12-23 22:13:13 +0000623 f = v->ob_type->tp_compare;
624 if (f != NULL && f == w->ob_type->tp_compare) {
Guido van Rossume797ec12001-01-17 15:24:28 +0000625 c = (*f)(v, w);
626 Py_DECREF(v);
627 Py_DECREF(w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000628 return adjust_tp_compare(c);
Guido van Rossume797ec12001-01-17 15:24:28 +0000629 }
630
Guido van Rossume797ec12001-01-17 15:24:28 +0000631 /* No comparison defined */
632 Py_DECREF(v);
633 Py_DECREF(w);
634 return 2;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000635}
636
Guido van Rossume797ec12001-01-17 15:24:28 +0000637/* Final fallback 3-way comparison, returning an int. Return:
638 -2 if an error occurred;
Tim Petersc99213f2001-11-04 05:57:16 +0000639 -1 if v < w;
640 0 if v == w;
641 1 if v > w.
Guido van Rossume797ec12001-01-17 15:24:28 +0000642*/
643static int
644default_3way_compare(PyObject *v, PyObject *w)
645{
646 int c;
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000647 char *vname, *wname;
Guido van Rossume797ec12001-01-17 15:24:28 +0000648
649 if (v->ob_type == w->ob_type) {
Barry Warsawb0e754d2001-01-20 06:24:55 +0000650 /* When comparing these pointers, they must be cast to
651 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
652 * uintptr_t). ANSI specifies that pointer compares other
653 * than == and != to non-related structures are undefined.
654 */
Barry Warsaw71ff8d52001-01-20 06:08:10 +0000655 Py_uintptr_t vv = (Py_uintptr_t)v;
656 Py_uintptr_t ww = (Py_uintptr_t)w;
Guido van Rossume797ec12001-01-17 15:24:28 +0000657 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
658 }
659
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000660#ifdef Py_USING_UNICODE
Guido van Rossume797ec12001-01-17 15:24:28 +0000661 /* Special case for Unicode */
662 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
663 c = PyUnicode_Compare(v, w);
664 if (!PyErr_Occurred())
665 return c;
666 /* TypeErrors are ignored: if Unicode coercion fails due
667 to one of the arguments not having the right type, we
668 continue as defined by the coercion protocol (see
669 above). Luckily, decoding errors are reported as
670 ValueErrors and are not masked by this technique. */
671 if (!PyErr_ExceptionMatches(PyExc_TypeError))
672 return -2;
673 PyErr_Clear();
674 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000675#endif
Guido van Rossume797ec12001-01-17 15:24:28 +0000676
Guido van Rossum0871e932001-01-22 19:28:09 +0000677 /* None is smaller than anything */
678 if (v == Py_None)
679 return -1;
680 if (w == Py_None)
681 return 1;
682
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000683 /* different type: compare type names; numbers are smaller */
684 if (PyNumber_Check(v))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000685 vname = "";
686 else
687 vname = v->ob_type->tp_name;
Guido van Rossumfb50d3f2003-02-18 16:40:09 +0000688 if (PyNumber_Check(w))
Guido van Rossum8f9143d2001-01-22 15:59:32 +0000689 wname = "";
690 else
691 wname = w->ob_type->tp_name;
692 c = strcmp(vname, wname);
693 if (c < 0)
694 return -1;
695 if (c > 0)
696 return 1;
697 /* Same type name, or (more likely) incomparable numeric types */
698 return ((Py_uintptr_t)(v->ob_type) < (
699 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
Guido van Rossume797ec12001-01-17 15:24:28 +0000700}
701
Tim Peters6d60b2e2001-05-07 20:53:51 +0000702/* Do a 3-way comparison, by hook or by crook. Return:
Guido van Rossuma4073002002-05-31 20:03:54 +0000703 -2 for an exception (but see below);
Tim Petersc99213f2001-11-04 05:57:16 +0000704 -1 if v < w;
Tim Peters6d60b2e2001-05-07 20:53:51 +0000705 0 if v == w;
Tim Petersc99213f2001-11-04 05:57:16 +0000706 1 if v > w;
Guido van Rossuma4073002002-05-31 20:03:54 +0000707 BUT: if the object implements a tp_compare function, it returns
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000708 whatever this function returns (whether with an exception or not).
Tim Peters6d60b2e2001-05-07 20:53:51 +0000709*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000710static int
Fred Drake100814d2000-07-09 15:48:49 +0000711do_cmp(PyObject *v, PyObject *w)
Guido van Rossum20566841995-01-12 11:26:10 +0000712{
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000713 int c;
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000714 cmpfunc f;
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000715
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000716 if (v->ob_type == w->ob_type
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000717 && (f = v->ob_type->tp_compare) != NULL) {
718 c = (*f)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000719 if (PyInstance_Check(v)) {
720 /* Instance tp_compare has a different signature.
721 But if it returns undefined we fall through. */
722 if (c != 2)
723 return c;
Neal Norwitz3f8dae72002-05-31 20:23:33 +0000724 /* Else fall through to try_rich_to_3way_compare() */
Guido van Rossuma4073002002-05-31 20:03:54 +0000725 }
726 else
727 return adjust_tp_compare(c);
Guido van Rossum82fc51c2001-08-16 08:02:45 +0000728 }
Guido van Rossuma4073002002-05-31 20:03:54 +0000729 /* We only get here if one of the following is true:
730 a) v and w have different types
731 b) v and w have the same type, which doesn't have tp_compare
732 c) v and w are instances, and either __cmp__ is not defined or
733 __cmp__ returns NotImplemented
734 */
Guido van Rossume797ec12001-01-17 15:24:28 +0000735 c = try_rich_to_3way_compare(v, w);
736 if (c < 2)
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000737 return c;
Guido van Rossume797ec12001-01-17 15:24:28 +0000738 c = try_3way_compare(v, w);
739 if (c < 2)
740 return c;
741 return default_3way_compare(v, w);
Guido van Rossum20566841995-01-12 11:26:10 +0000742}
743
Tim Petersc99213f2001-11-04 05:57:16 +0000744/* Compare v to w. Return
745 -1 if v < w or exception (PyErr_Occurred() true in latter case).
746 0 if v == w.
747 1 if v > w.
748 XXX The docs (C API manual) say the return value is undefined in case
749 XXX of error.
750*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000751int
Fred Drake100814d2000-07-09 15:48:49 +0000752PyObject_Compare(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000753{
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000754 int result;
755
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000756 if (v == NULL || w == NULL) {
757 PyErr_BadInternalCall();
758 return -1;
759 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760 if (v == w)
761 return 0;
Armin Rigo2b3eb402003-10-28 12:05:48 +0000762 if (Py_EnterRecursiveCall(" in cmp"))
763 return -1;
764 result = do_cmp(v, w);
765 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000766 return result < 0 ? -1 : result;
767}
768
Tim Petersc99213f2001-11-04 05:57:16 +0000769/* Return (new reference to) Py_True or Py_False. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000770static PyObject *
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000771convert_3way_to_object(int op, int c)
Guido van Rossume797ec12001-01-17 15:24:28 +0000772{
Guido van Rossume797ec12001-01-17 15:24:28 +0000773 PyObject *result;
Guido van Rossume797ec12001-01-17 15:24:28 +0000774 switch (op) {
775 case Py_LT: c = c < 0; break;
776 case Py_LE: c = c <= 0; break;
777 case Py_EQ: c = c == 0; break;
778 case Py_NE: c = c != 0; break;
779 case Py_GT: c = c > 0; break;
780 case Py_GE: c = c >= 0; break;
781 }
782 result = c ? Py_True : Py_False;
783 Py_INCREF(result);
Jeremy Hylton4a3dd2d2000-04-14 19:13:24 +0000784 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000785}
Tim Peters803526b2002-07-07 05:13:56 +0000786
Tim Petersc99213f2001-11-04 05:57:16 +0000787/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
788 Return
789 NULL if error
790 Py_True if v op w
791 Py_False if not (v op w)
792*/
Martin v. Löwis0163d6d2001-06-09 07:34:05 +0000793static PyObject *
794try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
795{
796 int c;
797
798 c = try_3way_compare(v, w);
799 if (c >= 2)
800 c = default_3way_compare(v, w);
801 if (c <= -2)
802 return NULL;
803 return convert_3way_to_object(op, c);
804}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805
Tim Petersc99213f2001-11-04 05:57:16 +0000806/* Do rich comparison on v and w. Return
807 NULL if error
808 Else a new reference to an object other than Py_NotImplemented, usually(?):
809 Py_True if v op w
810 Py_False if not (v op w)
811*/
Neil Schemenauerd38855c2001-01-21 16:25:18 +0000812static PyObject *
Guido van Rossume797ec12001-01-17 15:24:28 +0000813do_richcmp(PyObject *v, PyObject *w, int op)
814{
815 PyObject *res;
816
817 res = try_rich_compare(v, w, op);
818 if (res != Py_NotImplemented)
819 return res;
820 Py_DECREF(res);
821
822 return try_3way_to_rich_compare(v, w, op);
823}
824
Tim Petersc99213f2001-11-04 05:57:16 +0000825/* Return:
826 NULL for exception;
Tim Petersc99213f2001-11-04 05:57:16 +0000827 some object not equal to NotImplemented if it is implemented
828 (this latter object may not be a Boolean).
829*/
Guido van Rossume797ec12001-01-17 15:24:28 +0000830PyObject *
831PyObject_RichCompare(PyObject *v, PyObject *w, int op)
832{
833 PyObject *res;
834
835 assert(Py_LT <= op && op <= Py_GE);
Armin Rigo2b3eb402003-10-28 12:05:48 +0000836 if (Py_EnterRecursiveCall(" in cmp"))
837 return NULL;
Guido van Rossume797ec12001-01-17 15:24:28 +0000838
Armin Rigo2b3eb402003-10-28 12:05:48 +0000839 /* If the types are equal, and not old-style instances, try to
Tim Peters67754e92001-11-04 07:29:31 +0000840 get out cheap (don't bother with coercions etc.). */
841 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
842 cmpfunc fcmp;
843 richcmpfunc frich = RICHCOMPARE(v->ob_type);
844 /* If the type has richcmp, try it first. try_rich_compare
845 tries it two-sided, which is not needed since we've a
846 single type only. */
847 if (frich != NULL) {
848 res = (*frich)(v, w, op);
849 if (res != Py_NotImplemented)
850 goto Done;
851 Py_DECREF(res);
852 }
853 /* No richcmp, or this particular richmp not implemented.
854 Try 3-way cmp. */
855 fcmp = v->ob_type->tp_compare;
856 if (fcmp != NULL) {
857 int c = (*fcmp)(v, w);
Guido van Rossuma4073002002-05-31 20:03:54 +0000858 c = adjust_tp_compare(c);
859 if (c == -2) {
Tim Peters67754e92001-11-04 07:29:31 +0000860 res = NULL;
861 goto Done;
862 }
863 res = convert_3way_to_object(op, c);
864 goto Done;
865 }
Guido van Rossum2ffbf6b2001-01-17 21:27:02 +0000866 }
Tim Peters67754e92001-11-04 07:29:31 +0000867
868 /* Fast path not taken, or couldn't deliver a useful result. */
869 res = do_richcmp(v, w, op);
870Done:
Armin Rigo2b3eb402003-10-28 12:05:48 +0000871 Py_LeaveRecursiveCall();
Guido van Rossume797ec12001-01-17 15:24:28 +0000872 return res;
873}
874
Tim Petersde9725f2001-05-05 10:06:17 +0000875/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
Guido van Rossume797ec12001-01-17 15:24:28 +0000876int
877PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
878{
Raymond Hettinger93d44812004-03-21 17:01:44 +0000879 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000880 int ok;
881
Raymond Hettinger93d44812004-03-21 17:01:44 +0000882 /* Quick result when objects are the same.
883 Guarantees that identity implies equality. */
884 if (v == w) {
885 if (op == Py_EQ)
886 return 1;
887 else if (op == Py_NE)
888 return 0;
889 }
890
891 res = PyObject_RichCompare(v, w, op);
Guido van Rossume797ec12001-01-17 15:24:28 +0000892 if (res == NULL)
893 return -1;
Guido van Rossum81912d42002-08-24 05:33:28 +0000894 if (PyBool_Check(res))
895 ok = (res == Py_True);
896 else
897 ok = PyObject_IsTrue(res);
Guido van Rossume797ec12001-01-17 15:24:28 +0000898 Py_DECREF(res);
899 return ok;
900}
Fred Drake13634cf2000-06-29 19:17:04 +0000901
902/* Set of hash utility functions to help maintaining the invariant that
Raymond Hettinger8183fa42004-03-21 17:35:06 +0000903 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000904
905 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
906*/
907
908long
Fred Drake100814d2000-07-09 15:48:49 +0000909_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000910{
Tim Peters39dce292000-08-15 03:34:48 +0000911 double intpart, fractpart;
912 int expo;
913 long hipart;
914 long x; /* the final hash value */
915 /* This is designed so that Python numbers of different types
916 * that compare equal hash to the same value; otherwise comparisons
917 * of mapping keys will turn out weird.
918 */
919
Tim Peters39dce292000-08-15 03:34:48 +0000920 fractpart = modf(v, &intpart);
Tim Peters39dce292000-08-15 03:34:48 +0000921 if (fractpart == 0.0) {
922 /* This must return the same hash as an equal int or long. */
923 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
924 /* Convert to long and use its hash. */
925 PyObject *plong; /* converted to Python long */
926 if (Py_IS_INFINITY(intpart))
927 /* can't convert to long int -- arbitrary */
928 v = v < 0 ? -271828.0 : 314159.0;
929 plong = PyLong_FromDouble(v);
930 if (plong == NULL)
931 return -1;
932 x = PyObject_Hash(plong);
933 Py_DECREF(plong);
934 return x;
935 }
936 /* Fits in a C long == a Python int, so is its own hash. */
937 x = (long)intpart;
938 if (x == -1)
939 x = -2;
940 return x;
941 }
942 /* The fractional part is non-zero, so we don't have to worry about
943 * making this match the hash of some other type.
944 * Use frexp to get at the bits in the double.
Fred Drake13634cf2000-06-29 19:17:04 +0000945 * Since the VAX D double format has 56 mantissa bits, which is the
946 * most of any double format in use, each of these parts may have as
947 * many as (but no more than) 56 significant bits.
Tim Peters39dce292000-08-15 03:34:48 +0000948 * So, assuming sizeof(long) >= 4, each part can be broken into two
949 * longs; frexp and multiplication are used to do that.
950 * Also, since the Cray double format has 15 exponent bits, which is
951 * the most of any double format in use, shifting the exponent field
952 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
Fred Drake13634cf2000-06-29 19:17:04 +0000953 */
Tim Peters39dce292000-08-15 03:34:48 +0000954 v = frexp(v, &expo);
955 v *= 2147483648.0; /* 2**31 */
956 hipart = (long)v; /* take the top 32 bits */
957 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
958 x = hipart + (long)v + (expo << 15);
959 if (x == -1)
960 x = -2;
961 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000962}
963
964long
Fred Drake100814d2000-07-09 15:48:49 +0000965_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000966{
967#if SIZEOF_LONG >= SIZEOF_VOID_P
968 return (long)p;
969#else
970 /* convert to a Python long and hash that */
971 PyObject* longobj;
972 long x;
Tim Peters803526b2002-07-07 05:13:56 +0000973
Fred Drake13634cf2000-06-29 19:17:04 +0000974 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
975 x = -1;
976 goto finally;
977 }
978 x = PyObject_Hash(longobj);
Tim Peters803526b2002-07-07 05:13:56 +0000979
Fred Drake13634cf2000-06-29 19:17:04 +0000980finally:
981 Py_XDECREF(longobj);
982 return x;
983#endif
984}
985
986
Guido van Rossum9bfef441993-03-29 10:43:31 +0000987long
Fred Drake100814d2000-07-09 15:48:49 +0000988PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000989{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000990 PyTypeObject *tp = v->ob_type;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000991 if (tp->tp_hash != NULL)
992 return (*tp->tp_hash)(v);
Guido van Rossumd1f06b92001-01-24 22:14:43 +0000993 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
Fred Drake13634cf2000-06-29 19:17:04 +0000994 return _Py_HashPointer(v); /* Use address as hash value */
995 }
Guido van Rossum9bfef441993-03-29 10:43:31 +0000996 /* If there's a cmp but no hash defined, the object can't be hashed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997 PyErr_SetString(PyExc_TypeError, "unhashable type");
Guido van Rossum9bfef441993-03-29 10:43:31 +0000998 return -1;
999}
1000
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001001PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001002PyObject_GetAttrString(PyObject *v, char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001003{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001004 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001005
Tim Peters6d6c1a32001-08-02 04:15:00 +00001006 if (v->ob_type->tp_getattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001007 return (*v->ob_type->tp_getattr)(v, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001008 w = PyString_InternFromString(name);
1009 if (w == NULL)
1010 return NULL;
1011 res = PyObject_GetAttr(v, w);
1012 Py_XDECREF(w);
1013 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001014}
1015
1016int
Fred Drake100814d2000-07-09 15:48:49 +00001017PyObject_HasAttrString(PyObject *v, char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001018{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019 PyObject *res = PyObject_GetAttrString(v, name);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001020 if (res != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001021 Py_DECREF(res);
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001022 return 1;
1023 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024 PyErr_Clear();
Guido van Rossumed18fdc1993-07-11 19:55:34 +00001025 return 0;
1026}
1027
1028int
Fred Drake100814d2000-07-09 15:48:49 +00001029PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001030{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031 PyObject *s;
1032 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +00001033
Tim Peters6d6c1a32001-08-02 04:15:00 +00001034 if (v->ob_type->tp_setattr != NULL)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001035 return (*v->ob_type->tp_setattr)(v, name, w);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036 s = PyString_InternFromString(name);
1037 if (s == NULL)
1038 return -1;
1039 res = PyObject_SetAttr(v, s, w);
1040 Py_XDECREF(s);
1041 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001042}
1043
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001044PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001045PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001046{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047 PyTypeObject *tp = v->ob_type;
1048
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001049 if (!PyString_Check(name)) {
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001050#ifdef Py_USING_UNICODE
1051 /* The Unicode to string conversion is done here because the
1052 existing tp_getattro slots expect a string object as name
1053 and we wouldn't want to break those. */
1054 if (PyUnicode_Check(name)) {
1055 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1056 if (name == NULL)
1057 return NULL;
1058 }
1059 else
1060#endif
1061 {
1062 PyErr_SetString(PyExc_TypeError,
1063 "attribute name must be string");
1064 return NULL;
1065 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001066 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001067 if (tp->tp_getattro != NULL)
1068 return (*tp->tp_getattro)(v, name);
1069 if (tp->tp_getattr != NULL)
1070 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1071 PyErr_Format(PyExc_AttributeError,
1072 "'%.50s' object has no attribute '%.400s'",
1073 tp->tp_name, PyString_AS_STRING(name));
1074 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001075}
1076
1077int
Fred Drake100814d2000-07-09 15:48:49 +00001078PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001079{
1080 PyObject *res = PyObject_GetAttr(v, name);
1081 if (res != NULL) {
1082 Py_DECREF(res);
1083 return 1;
1084 }
1085 PyErr_Clear();
1086 return 0;
1087}
1088
1089int
Fred Drake100814d2000-07-09 15:48:49 +00001090PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001091{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001092 PyTypeObject *tp = v->ob_type;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001093 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001094
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001095 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001096#ifdef Py_USING_UNICODE
1097 /* The Unicode to string conversion is done here because the
1098 existing tp_setattro slots expect a string object as name
1099 and we wouldn't want to break those. */
1100 if (PyUnicode_Check(name)) {
1101 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1102 if (name == NULL)
1103 return -1;
1104 }
Tim Peters803526b2002-07-07 05:13:56 +00001105 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001106#endif
1107 {
1108 PyErr_SetString(PyExc_TypeError,
1109 "attribute name must be string");
1110 return -1;
1111 }
Jeremy Hylton99a8f902000-06-23 14:36:32 +00001112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113 else
1114 Py_INCREF(name);
1115
1116 PyString_InternInPlace(&name);
1117 if (tp->tp_setattro != NULL) {
1118 err = (*tp->tp_setattro)(v, name, value);
1119 Py_DECREF(name);
1120 return err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001121 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122 if (tp->tp_setattr != NULL) {
1123 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1124 Py_DECREF(name);
1125 return err;
1126 }
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001127 Py_DECREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001128 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1129 PyErr_Format(PyExc_TypeError,
1130 "'%.100s' object has no attributes "
1131 "(%s .%.100s)",
1132 tp->tp_name,
1133 value==NULL ? "del" : "assign to",
1134 PyString_AS_STRING(name));
1135 else
1136 PyErr_Format(PyExc_TypeError,
1137 "'%.100s' object has only read-only attributes "
1138 "(%s .%.100s)",
1139 tp->tp_name,
1140 value==NULL ? "del" : "assign to",
1141 PyString_AS_STRING(name));
1142 return -1;
1143}
1144
1145/* Helper to get a pointer to an object's __dict__ slot, if any */
1146
1147PyObject **
1148_PyObject_GetDictPtr(PyObject *obj)
1149{
Tim Peters6d6c1a32001-08-02 04:15:00 +00001150 long dictoffset;
1151 PyTypeObject *tp = obj->ob_type;
1152
1153 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1154 return NULL;
1155 dictoffset = tp->tp_dictoffset;
1156 if (dictoffset == 0)
1157 return NULL;
1158 if (dictoffset < 0) {
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001159 int tsize;
1160 size_t size;
1161
1162 tsize = ((PyVarObject *)obj)->ob_size;
1163 if (tsize < 0)
1164 tsize = -tsize;
1165 size = _PyObject_VAR_SIZE(tp, tsize);
1166
Tim Peters6d483d32001-10-06 21:27:34 +00001167 dictoffset += (long)size;
1168 assert(dictoffset > 0);
1169 assert(dictoffset % SIZEOF_VOID_P == 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001170 }
1171 return (PyObject **) ((char *)obj + dictoffset);
1172}
1173
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001175PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001176{
1177 Py_INCREF(obj);
1178 return obj;
1179}
1180
Michael W. Hudson1593f502004-09-14 17:09:47 +00001181/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1182
Raymond Hettinger01538262003-03-17 08:24:35 +00001183PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00001184PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1185{
1186 PyTypeObject *tp = obj->ob_type;
Guido van Rossum056fbf42002-08-19 19:22:50 +00001187 PyObject *descr = NULL;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001188 PyObject *res = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001189 descrgetfunc f;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001190 long dictoffset;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191 PyObject **dictptr;
1192
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001193 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001194#ifdef Py_USING_UNICODE
1195 /* The Unicode to string conversion is done here because the
1196 existing tp_setattro slots expect a string object as name
1197 and we wouldn't want to break those. */
1198 if (PyUnicode_Check(name)) {
1199 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1200 if (name == NULL)
1201 return NULL;
1202 }
Tim Peters803526b2002-07-07 05:13:56 +00001203 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001204#endif
1205 {
1206 PyErr_SetString(PyExc_TypeError,
1207 "attribute name must be string");
1208 return NULL;
1209 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001210 }
1211 else
1212 Py_INCREF(name);
1213
Tim Peters6d6c1a32001-08-02 04:15:00 +00001214 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001215 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001216 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217 }
1218
Guido van Rossum056fbf42002-08-19 19:22:50 +00001219 /* Inline _PyType_Lookup */
1220 {
1221 int i, n;
1222 PyObject *mro, *base, *dict;
1223
1224 /* Look in tp_dict of types in MRO */
1225 mro = tp->tp_mro;
1226 assert(mro != NULL);
1227 assert(PyTuple_Check(mro));
1228 n = PyTuple_GET_SIZE(mro);
1229 for (i = 0; i < n; i++) {
1230 base = PyTuple_GET_ITEM(mro, i);
1231 if (PyClass_Check(base))
1232 dict = ((PyClassObject *)base)->cl_dict;
1233 else {
1234 assert(PyType_Check(base));
1235 dict = ((PyTypeObject *)base)->tp_dict;
1236 }
1237 assert(dict && PyDict_Check(dict));
1238 descr = PyDict_GetItem(dict, name);
1239 if (descr != NULL)
1240 break;
1241 }
1242 }
1243
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001244 Py_XINCREF(descr);
1245
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001247 if (descr != NULL &&
1248 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249 f = descr->ob_type->tp_descr_get;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001250 if (f != NULL && PyDescr_IsData(descr)) {
1251 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001252 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001253 goto done;
1254 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001255 }
1256
Guido van Rossumc66ff442002-08-19 16:50:48 +00001257 /* Inline _PyObject_GetDictPtr */
1258 dictoffset = tp->tp_dictoffset;
1259 if (dictoffset != 0) {
1260 PyObject *dict;
1261 if (dictoffset < 0) {
1262 int tsize;
1263 size_t size;
1264
1265 tsize = ((PyVarObject *)obj)->ob_size;
1266 if (tsize < 0)
1267 tsize = -tsize;
1268 size = _PyObject_VAR_SIZE(tp, tsize);
1269
1270 dictoffset += (long)size;
1271 assert(dictoffset > 0);
1272 assert(dictoffset % SIZEOF_VOID_P == 0);
1273 }
1274 dictptr = (PyObject **) ((char *)obj + dictoffset);
1275 dict = *dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276 if (dict != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001277 res = PyDict_GetItem(dict, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278 if (res != NULL) {
1279 Py_INCREF(res);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001280 Py_XDECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001281 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282 }
1283 }
1284 }
1285
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001286 if (f != NULL) {
1287 res = f(descr, obj, (PyObject *)obj->ob_type);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001288 Py_DECREF(descr);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001289 goto done;
1290 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291
1292 if (descr != NULL) {
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001293 res = descr;
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001294 /* descr was already increfed above */
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001295 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 }
1297
1298 PyErr_Format(PyExc_AttributeError,
1299 "'%.50s' object has no attribute '%.400s'",
1300 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001301 done:
1302 Py_DECREF(name);
1303 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304}
1305
1306int
1307PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1308{
1309 PyTypeObject *tp = obj->ob_type;
1310 PyObject *descr;
1311 descrsetfunc f;
1312 PyObject **dictptr;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001313 int res = -1;
1314
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001315 if (!PyString_Check(name)){
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001316#ifdef Py_USING_UNICODE
1317 /* The Unicode to string conversion is done here because the
1318 existing tp_setattro slots expect a string object as name
1319 and we wouldn't want to break those. */
1320 if (PyUnicode_Check(name)) {
1321 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1322 if (name == NULL)
1323 return -1;
1324 }
Tim Peters803526b2002-07-07 05:13:56 +00001325 else
Martin v. Löwis0c160a02002-03-15 13:40:30 +00001326#endif
1327 {
1328 PyErr_SetString(PyExc_TypeError,
1329 "attribute name must be string");
1330 return -1;
1331 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001332 }
1333 else
1334 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335
1336 if (tp->tp_dict == NULL) {
Guido van Rossum528b7eb2001-08-07 17:24:28 +00001337 if (PyType_Ready(tp) < 0)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001338 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339 }
1340
1341 descr = _PyType_Lookup(tp, name);
1342 f = NULL;
Guido van Rossum90195e22003-02-19 03:19:29 +00001343 if (descr != NULL &&
1344 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001345 f = descr->ob_type->tp_descr_set;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001346 if (f != NULL && PyDescr_IsData(descr)) {
1347 res = f(descr, obj, value);
1348 goto done;
1349 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350 }
1351
1352 dictptr = _PyObject_GetDictPtr(obj);
1353 if (dictptr != NULL) {
1354 PyObject *dict = *dictptr;
1355 if (dict == NULL && value != NULL) {
1356 dict = PyDict_New();
1357 if (dict == NULL)
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001358 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359 *dictptr = dict;
1360 }
1361 if (dict != NULL) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001362 if (value == NULL)
1363 res = PyDict_DelItem(dict, name);
1364 else
1365 res = PyDict_SetItem(dict, name, value);
1366 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1367 PyErr_SetObject(PyExc_AttributeError, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001368 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369 }
1370 }
1371
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001372 if (f != NULL) {
1373 res = f(descr, obj, value);
1374 goto done;
1375 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001376
1377 if (descr == NULL) {
1378 PyErr_Format(PyExc_AttributeError,
1379 "'%.50s' object has no attribute '%.400s'",
1380 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001381 goto done;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001382 }
1383
1384 PyErr_Format(PyExc_AttributeError,
1385 "'%.50s' object attribute '%.400s' is read-only",
1386 tp->tp_name, PyString_AS_STRING(name));
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001387 done:
1388 Py_DECREF(name);
1389 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001390}
1391
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001392/* Test a value used as condition, e.g., in a for or if statement.
1393 Return -1 if an error occurred */
1394
1395int
Fred Drake100814d2000-07-09 15:48:49 +00001396PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001397{
1398 int res;
Guido van Rossum6248f442002-08-24 06:31:34 +00001399 if (v == Py_True)
1400 return 1;
1401 if (v == Py_False)
1402 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001403 if (v == Py_None)
Neal Norwitz51290d32002-06-13 21:32:44 +00001404 return 0;
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001405 else if (v->ob_type->tp_as_number != NULL &&
1406 v->ob_type->tp_as_number->nb_nonzero != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001407 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001408 else if (v->ob_type->tp_as_mapping != NULL &&
1409 v->ob_type->tp_as_mapping->mp_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001410 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
Guido van Rossum1c4f4581998-05-22 00:53:24 +00001411 else if (v->ob_type->tp_as_sequence != NULL &&
1412 v->ob_type->tp_as_sequence->sq_length != NULL)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001413 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1414 else
Neal Norwitz51290d32002-06-13 21:32:44 +00001415 return 1;
1416 return (res > 0) ? 1 : res;
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001417}
1418
Tim Peters803526b2002-07-07 05:13:56 +00001419/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001420 Return -1 if an error occurred */
1421
1422int
Fred Drake100814d2000-07-09 15:48:49 +00001423PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001424{
1425 int res;
1426 res = PyObject_IsTrue(v);
1427 if (res < 0)
1428 return res;
1429 return res == 0;
1430}
1431
Guido van Rossum5524a591995-01-10 15:26:20 +00001432/* Coerce two numeric types to the "larger" one.
1433 Increment the reference count on each argument.
Guido van Rossume797ec12001-01-17 15:24:28 +00001434 Return value:
1435 -1 if an error occurred;
1436 0 if the coercion succeeded (and then the reference counts are increased);
1437 1 if no coercion is possible (and no error is raised).
Guido van Rossum5524a591995-01-10 15:26:20 +00001438*/
Guido van Rossum5524a591995-01-10 15:26:20 +00001439int
Fred Drake100814d2000-07-09 15:48:49 +00001440PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
Guido van Rossum5524a591995-01-10 15:26:20 +00001441{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001442 register PyObject *v = *pv;
1443 register PyObject *w = *pw;
Guido van Rossum5524a591995-01-10 15:26:20 +00001444 int res;
1445
Guido van Rossum517c7d42002-04-26 02:49:14 +00001446 /* Shortcut only for old-style types */
1447 if (v->ob_type == w->ob_type &&
1448 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1449 {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001450 Py_INCREF(v);
1451 Py_INCREF(w);
Guido van Rossum5524a591995-01-10 15:26:20 +00001452 return 0;
1453 }
1454 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1455 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1456 if (res <= 0)
1457 return res;
1458 }
1459 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1460 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1461 if (res <= 0)
1462 return res;
1463 }
Guido van Rossum242c6421997-11-19 16:03:17 +00001464 return 1;
1465}
1466
Guido van Rossume797ec12001-01-17 15:24:28 +00001467/* Coerce two numeric types to the "larger" one.
1468 Increment the reference count on each argument.
1469 Return -1 and raise an exception if no coercion is possible
1470 (and then no reference count is incremented).
1471*/
Guido van Rossum242c6421997-11-19 16:03:17 +00001472int
Fred Drake100814d2000-07-09 15:48:49 +00001473PyNumber_Coerce(PyObject **pv, PyObject **pw)
Guido van Rossum242c6421997-11-19 16:03:17 +00001474{
1475 int err = PyNumber_CoerceEx(pv, pw);
1476 if (err <= 0)
1477 return err;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001478 PyErr_SetString(PyExc_TypeError, "number coercion failed");
Guido van Rossum5524a591995-01-10 15:26:20 +00001479 return -1;
1480}
1481
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001482
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001483/* Test whether an object can be called */
1484
1485int
Fred Drake100814d2000-07-09 15:48:49 +00001486PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001487{
1488 if (x == NULL)
1489 return 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001490 if (PyInstance_Check(x)) {
1491 PyObject *call = PyObject_GetAttrString(x, "__call__");
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001492 if (call == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001493 PyErr_Clear();
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001494 return 0;
1495 }
1496 /* Could test recursively but don't, for fear of endless
1497 recursion if some joker sets self.__call__ = self */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001498 Py_DECREF(call);
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001499 return 1;
1500 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001501 else {
1502 return x->ob_type->tp_call != NULL;
1503 }
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001504}
1505
Tim Peters7eea37e2001-09-04 22:08:56 +00001506/* Helper for PyObject_Dir.
1507 Merge the __dict__ of aclass into dict, and recursively also all
1508 the __dict__s of aclass's base classes. The order of merging isn't
1509 defined, as it's expected that only the final set of dict keys is
1510 interesting.
1511 Return 0 on success, -1 on error.
1512*/
1513
1514static int
1515merge_class_dict(PyObject* dict, PyObject* aclass)
1516{
1517 PyObject *classdict;
1518 PyObject *bases;
1519
1520 assert(PyDict_Check(dict));
1521 assert(aclass);
1522
1523 /* Merge in the type's dict (if any). */
1524 classdict = PyObject_GetAttrString(aclass, "__dict__");
1525 if (classdict == NULL)
1526 PyErr_Clear();
1527 else {
1528 int status = PyDict_Update(dict, classdict);
1529 Py_DECREF(classdict);
1530 if (status < 0)
1531 return -1;
1532 }
1533
1534 /* Recursively merge in the base types' (if any) dicts. */
1535 bases = PyObject_GetAttrString(aclass, "__bases__");
Tim Petersbc7e8632001-09-16 20:33:22 +00001536 if (bases == NULL)
1537 PyErr_Clear();
1538 else {
Guido van Rossum44022412002-05-13 18:29:46 +00001539 /* We have no guarantee that bases is a real tuple */
Tim Peters7eea37e2001-09-04 22:08:56 +00001540 int i, n;
Guido van Rossum44022412002-05-13 18:29:46 +00001541 n = PySequence_Size(bases); /* This better be right */
1542 if (n < 0)
1543 PyErr_Clear();
1544 else {
1545 for (i = 0; i < n; i++) {
Tim Peters18e70832003-02-05 19:35:19 +00001546 int status;
Guido van Rossum44022412002-05-13 18:29:46 +00001547 PyObject *base = PySequence_GetItem(bases, i);
1548 if (base == NULL) {
1549 Py_DECREF(bases);
1550 return -1;
1551 }
Tim Peters18e70832003-02-05 19:35:19 +00001552 status = merge_class_dict(dict, base);
1553 Py_DECREF(base);
1554 if (status < 0) {
Guido van Rossum44022412002-05-13 18:29:46 +00001555 Py_DECREF(bases);
1556 return -1;
1557 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001558 }
1559 }
1560 Py_DECREF(bases);
1561 }
1562 return 0;
1563}
1564
Tim Peters305b5852001-09-17 02:38:46 +00001565/* Helper for PyObject_Dir.
1566 If obj has an attr named attrname that's a list, merge its string
1567 elements into keys of dict.
1568 Return 0 on success, -1 on error. Errors due to not finding the attr,
1569 or the attr not being a list, are suppressed.
1570*/
1571
1572static int
1573merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1574{
1575 PyObject *list;
1576 int result = 0;
1577
1578 assert(PyDict_Check(dict));
1579 assert(obj);
1580 assert(attrname);
1581
1582 list = PyObject_GetAttrString(obj, attrname);
1583 if (list == NULL)
1584 PyErr_Clear();
1585
1586 else if (PyList_Check(list)) {
1587 int i;
1588 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1589 PyObject *item = PyList_GET_ITEM(list, i);
1590 if (PyString_Check(item)) {
1591 result = PyDict_SetItem(dict, item, Py_None);
1592 if (result < 0)
1593 break;
1594 }
1595 }
1596 }
1597
1598 Py_XDECREF(list);
1599 return result;
1600}
1601
Tim Peters7eea37e2001-09-04 22:08:56 +00001602/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1603 docstring, which should be kept in synch with this implementation. */
1604
1605PyObject *
1606PyObject_Dir(PyObject *arg)
1607{
1608 /* Set exactly one of these non-NULL before the end. */
1609 PyObject *result = NULL; /* result list */
1610 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1611
1612 /* If NULL arg, return the locals. */
1613 if (arg == NULL) {
1614 PyObject *locals = PyEval_GetLocals();
1615 if (locals == NULL)
1616 goto error;
Raymond Hettinger214b1c32004-07-02 06:41:07 +00001617 result = PyMapping_Keys(locals);
Tim Peters7eea37e2001-09-04 22:08:56 +00001618 if (result == NULL)
1619 goto error;
1620 }
1621
1622 /* Elif this is some form of module, we only want its dict. */
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001623 else if (PyModule_Check(arg)) {
Tim Peters7eea37e2001-09-04 22:08:56 +00001624 masterdict = PyObject_GetAttrString(arg, "__dict__");
1625 if (masterdict == NULL)
1626 goto error;
Guido van Rossum8dbd3d82001-09-10 18:27:43 +00001627 if (!PyDict_Check(masterdict)) {
1628 PyErr_SetString(PyExc_TypeError,
1629 "module.__dict__ is not a dictionary");
1630 goto error;
1631 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001632 }
1633
1634 /* Elif some form of type or class, grab its dict and its bases.
1635 We deliberately don't suck up its __class__, as methods belonging
1636 to the metaclass would probably be more confusing than helpful. */
1637 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1638 masterdict = PyDict_New();
1639 if (masterdict == NULL)
1640 goto error;
1641 if (merge_class_dict(masterdict, arg) < 0)
1642 goto error;
1643 }
1644
1645 /* Else look at its dict, and the attrs reachable from its class. */
1646 else {
1647 PyObject *itsclass;
1648 /* Create a dict to start with. CAUTION: Not everything
1649 responding to __dict__ returns a dict! */
1650 masterdict = PyObject_GetAttrString(arg, "__dict__");
1651 if (masterdict == NULL) {
1652 PyErr_Clear();
1653 masterdict = PyDict_New();
1654 }
1655 else if (!PyDict_Check(masterdict)) {
1656 Py_DECREF(masterdict);
1657 masterdict = PyDict_New();
1658 }
1659 else {
1660 /* The object may have returned a reference to its
1661 dict, so copy it to avoid mutating it. */
1662 PyObject *temp = PyDict_Copy(masterdict);
1663 Py_DECREF(masterdict);
1664 masterdict = temp;
1665 }
1666 if (masterdict == NULL)
1667 goto error;
1668
Tim Peters305b5852001-09-17 02:38:46 +00001669 /* Merge in __members__ and __methods__ (if any).
1670 XXX Would like this to go away someday; for now, it's
1671 XXX needed to get at im_self etc of method objects. */
1672 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1673 goto error;
1674 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1675 goto error;
1676
Tim Peters7eea37e2001-09-04 22:08:56 +00001677 /* Merge in attrs reachable from its class.
1678 CAUTION: Not all objects have a __class__ attr. */
1679 itsclass = PyObject_GetAttrString(arg, "__class__");
1680 if (itsclass == NULL)
1681 PyErr_Clear();
1682 else {
1683 int status = merge_class_dict(masterdict, itsclass);
1684 Py_DECREF(itsclass);
1685 if (status < 0)
1686 goto error;
1687 }
1688 }
1689
1690 assert((result == NULL) ^ (masterdict == NULL));
1691 if (masterdict != NULL) {
1692 /* The result comes from its keys. */
1693 assert(result == NULL);
1694 result = PyDict_Keys(masterdict);
1695 if (result == NULL)
1696 goto error;
1697 }
1698
1699 assert(result);
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001700 if (!PyList_Check(result)) {
Tim Petersf4aca752004-09-23 02:39:37 +00001701 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger2a7dede2004-08-07 04:55:30 +00001702 "Expected keys() to be a list.");
1703 goto error;
1704 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001705 if (PyList_Sort(result) != 0)
1706 goto error;
1707 else
1708 goto normal_return;
1709
1710 error:
1711 Py_XDECREF(result);
1712 result = NULL;
1713 /* fall through */
1714 normal_return:
1715 Py_XDECREF(masterdict);
1716 return result;
1717}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001718
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001719/*
1720NoObject is usable as a non-NULL undefined value, used by the macro None.
1721There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001722so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001723(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001724*/
1725
Guido van Rossum0c182a11992-03-27 17:26:13 +00001726/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001727static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001728none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001729{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001730 return PyString_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001731}
1732
Barry Warsaw9bf16442001-01-23 16:24:35 +00001733/* ARGUSED */
1734static void
Tim Peters803526b2002-07-07 05:13:56 +00001735none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001736{
1737 /* This should never get called, but we also don't want to SEGV if
1738 * we accidently decref None out of existance.
1739 */
Martin v. Löwis3f19b102002-08-07 16:21:51 +00001740 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001741}
1742
1743
Guido van Rossumba21a492001-08-16 08:17:26 +00001744static PyTypeObject PyNone_Type = {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001745 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001746 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001747 "NoneType",
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001748 0,
1749 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001750 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Guido van Rossum7066dd71992-09-17 17:54:56 +00001751 0, /*tp_print*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001752 0, /*tp_getattr*/
1753 0, /*tp_setattr*/
1754 0, /*tp_compare*/
Guido van Rossum1d5735e1994-08-30 08:27:36 +00001755 (reprfunc)none_repr, /*tp_repr*/
Guido van Rossum3f5da241990-12-20 15:06:42 +00001756 0, /*tp_as_number*/
1757 0, /*tp_as_sequence*/
1758 0, /*tp_as_mapping*/
Guido van Rossum9bfef441993-03-29 10:43:31 +00001759 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001760};
1761
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001762PyObject _Py_NoneStruct = {
Guido van Rossumba21a492001-08-16 08:17:26 +00001763 PyObject_HEAD_INIT(&PyNone_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001764};
1765
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001766/* NotImplemented is an object that can be used to signal that an
1767 operation is not implemented for the given type combination. */
1768
1769static PyObject *
1770NotImplemented_repr(PyObject *op)
1771{
1772 return PyString_FromString("NotImplemented");
1773}
1774
1775static PyTypeObject PyNotImplemented_Type = {
1776 PyObject_HEAD_INIT(&PyType_Type)
1777 0,
Guido van Rossumba21a492001-08-16 08:17:26 +00001778 "NotImplementedType",
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001779 0,
1780 0,
Barry Warsaw9bf16442001-01-23 16:24:35 +00001781 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001782 0, /*tp_print*/
1783 0, /*tp_getattr*/
1784 0, /*tp_setattr*/
1785 0, /*tp_compare*/
1786 (reprfunc)NotImplemented_repr, /*tp_repr*/
1787 0, /*tp_as_number*/
1788 0, /*tp_as_sequence*/
1789 0, /*tp_as_mapping*/
1790 0, /*tp_hash */
1791};
1792
1793PyObject _Py_NotImplementedStruct = {
1794 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1795};
1796
Guido van Rossumba21a492001-08-16 08:17:26 +00001797void
1798_Py_ReadyTypes(void)
1799{
1800 if (PyType_Ready(&PyType_Type) < 0)
1801 Py_FatalError("Can't initialize 'type'");
1802
Fred Drake0a4dd392004-07-02 18:57:45 +00001803 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1804 Py_FatalError("Can't initialize 'weakref'");
1805
Guido van Rossum77f6a652002-04-03 22:41:51 +00001806 if (PyType_Ready(&PyBool_Type) < 0)
1807 Py_FatalError("Can't initialize 'bool'");
1808
Guido van Rossumcacfc072002-05-24 19:01:59 +00001809 if (PyType_Ready(&PyString_Type) < 0)
1810 Py_FatalError("Can't initialize 'str'");
1811
Guido van Rossumba21a492001-08-16 08:17:26 +00001812 if (PyType_Ready(&PyList_Type) < 0)
1813 Py_FatalError("Can't initialize 'list'");
1814
1815 if (PyType_Ready(&PyNone_Type) < 0)
1816 Py_FatalError("Can't initialize type(None)");
1817
1818 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1819 Py_FatalError("Can't initialize type(NotImplemented)");
1820}
1821
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001822
Guido van Rossum84a90321996-05-22 16:34:47 +00001823#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001824
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001825void
Fred Drake100814d2000-07-09 15:48:49 +00001826_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001827{
Tim Peters34592512002-07-11 06:23:50 +00001828 _Py_INC_REFTOTAL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001829 op->ob_refcnt = 1;
Tim Peters7571a0f2003-03-23 17:52:28 +00001830 _Py_AddToAllObjects(op, 1);
Tim Peters34592512002-07-11 06:23:50 +00001831 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001832}
1833
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001834void
Fred Drake100814d2000-07-09 15:48:49 +00001835_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001836{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001837#ifdef SLOW_UNREF_CHECK
Guido van Rossum4c08d552000-03-10 22:55:18 +00001838 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001839#endif
Guido van Rossumd7047b31995-01-02 19:07:15 +00001840 if (op->ob_refcnt < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001841 Py_FatalError("UNREF negative refcnt");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001842 if (op == &refchain ||
Guido van Rossumd7047b31995-01-02 19:07:15 +00001843 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001844 Py_FatalError("UNREF invalid object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001845#ifdef SLOW_UNREF_CHECK
Guido van Rossum3f5da241990-12-20 15:06:42 +00001846 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1847 if (p == op)
1848 break;
1849 }
Guido van Rossumd7047b31995-01-02 19:07:15 +00001850 if (p == &refchain) /* Not found */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001851 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001852#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853 op->_ob_next->_ob_prev = op->_ob_prev;
1854 op->_ob_prev->_ob_next = op->_ob_next;
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001855 op->_ob_next = op->_ob_prev = NULL;
Tim Peters34592512002-07-11 06:23:50 +00001856 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001857}
1858
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001859void
Fred Drake100814d2000-07-09 15:48:49 +00001860_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001861{
Guido van Rossum9776adf1994-09-07 14:36:45 +00001862 destructor dealloc = op->ob_type->tp_dealloc;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001863 _Py_ForgetReference(op);
Guido van Rossum9776adf1994-09-07 14:36:45 +00001864 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001865}
1866
Tim Peters269b2a62003-04-17 19:52:29 +00001867/* Print all live objects. Because PyObject_Print is called, the
1868 * interpreter must be in a healthy state.
1869 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001870void
Fred Drake100814d2000-07-09 15:48:49 +00001871_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001872{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001873 PyObject *op;
Guido van Rossume09fb551997-08-05 02:04:34 +00001874 fprintf(fp, "Remaining objects:\n");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001875 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Tim Peters269b2a62003-04-17 19:52:29 +00001876 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001877 if (PyObject_Print(op, fp, 0) != 0)
1878 PyErr_Clear();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001879 putc('\n', fp);
1880 }
1881}
1882
Tim Peters269b2a62003-04-17 19:52:29 +00001883/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1884 * doesn't make any calls to the Python C API, so is always safe to call.
1885 */
1886void
1887_Py_PrintReferenceAddresses(FILE *fp)
1888{
1889 PyObject *op;
1890 fprintf(fp, "Remaining object addresses:\n");
1891 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Tim Peters21d7d4d2003-04-18 00:45:59 +00001892 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
1893 op->ob_type->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001894}
1895
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001896PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001897_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001898{
1899 int i, n;
1900 PyObject *t = NULL;
1901 PyObject *res, *op;
1902
1903 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1904 return NULL;
1905 op = refchain._ob_next;
1906 res = PyList_New(0);
1907 if (res == NULL)
1908 return NULL;
1909 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1910 while (op == self || op == args || op == res || op == t ||
Guido van Rossum3c296022001-07-14 17:58:00 +00001911 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001912 op = op->_ob_next;
1913 if (op == &refchain)
1914 return res;
1915 }
1916 if (PyList_Append(res, op) < 0) {
1917 Py_DECREF(res);
1918 return NULL;
1919 }
1920 op = op->_ob_next;
1921 }
1922 return res;
1923}
1924
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001925#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001926
1927
1928/* Hack to force loading of cobject.o */
Guido van Rossumda9c2711996-12-05 21:58:58 +00001929PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
Guido van Rossum84a90321996-05-22 16:34:47 +00001930
1931
1932/* Hack to force loading of abstract.o */
Neal Norwitz41785152002-06-13 21:42:51 +00001933int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001934
1935
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001936/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001937
Thomas Wouters334fb892000-07-25 12:56:38 +00001938void *
Fred Drake100814d2000-07-09 15:48:49 +00001939PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001940{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001941 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001942}
1943
Thomas Wouters334fb892000-07-25 12:56:38 +00001944void *
1945PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001946{
Tim Petersaf3e8de2002-04-12 07:22:56 +00001947 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001948}
1949
1950void
Thomas Wouters334fb892000-07-25 12:56:38 +00001951PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001952{
Guido van Rossumb18618d2000-05-03 23:44:39 +00001953 PyMem_FREE(p);
1954}
1955
1956
Guido van Rossum86610361998-04-10 22:32:46 +00001957/* These methods are used to control infinite recursion in repr, str, print,
1958 etc. Container objects that may recursively contain themselves,
1959 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1960 Py_ReprLeave() to avoid infinite recursion.
1961
1962 Py_ReprEnter() returns 0 the first time it is called for a particular
1963 object and 1 every time thereafter. It returns -1 if an exception
1964 occurred. Py_ReprLeave() has no return value.
1965
1966 See dictobject.c and listobject.c for examples of use.
1967*/
1968
1969#define KEY "Py_Repr"
1970
1971int
Fred Drake100814d2000-07-09 15:48:49 +00001972Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001973{
1974 PyObject *dict;
1975 PyObject *list;
1976 int i;
1977
1978 dict = PyThreadState_GetDict();
1979 if (dict == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001980 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001981 list = PyDict_GetItemString(dict, KEY);
1982 if (list == NULL) {
1983 list = PyList_New(0);
1984 if (list == NULL)
1985 return -1;
1986 if (PyDict_SetItemString(dict, KEY, list) < 0)
1987 return -1;
1988 Py_DECREF(list);
1989 }
1990 i = PyList_GET_SIZE(list);
1991 while (--i >= 0) {
1992 if (PyList_GET_ITEM(list, i) == obj)
1993 return 1;
1994 }
1995 PyList_Append(list, obj);
1996 return 0;
1997}
1998
1999void
Fred Drake100814d2000-07-09 15:48:49 +00002000Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002001{
2002 PyObject *dict;
2003 PyObject *list;
2004 int i;
2005
2006 dict = PyThreadState_GetDict();
Guido van Rossumeb909461998-04-11 15:17:34 +00002007 if (dict == NULL)
2008 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002009 list = PyDict_GetItemString(dict, KEY);
Guido van Rossumeb909461998-04-11 15:17:34 +00002010 if (list == NULL || !PyList_Check(list))
2011 return;
Guido van Rossum86610361998-04-10 22:32:46 +00002012 i = PyList_GET_SIZE(list);
2013 /* Count backwards because we always expect obj to be list[-1] */
2014 while (--i >= 0) {
2015 if (PyList_GET_ITEM(list, i) == obj) {
2016 PyList_SetSlice(list, i, i + 1, NULL);
2017 break;
2018 }
2019 }
2020}
Guido van Rossumd724b232000-03-13 16:01:29 +00002021
Tim Peters803526b2002-07-07 05:13:56 +00002022/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002023
Tim Peters803526b2002-07-07 05:13:56 +00002024/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002025int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00002026
Tim Peters803526b2002-07-07 05:13:56 +00002027/* List of objects that still need to be cleaned up, singly linked via their
2028 * gc headers' gc_prev pointers.
2029 */
2030PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00002031
Tim Peters803526b2002-07-07 05:13:56 +00002032/* Add op to the _PyTrash_delete_later list. Called when the current
2033 * call-stack depth gets large. op must be a currently untracked gc'ed
2034 * object, with refcount 0. Py_DECREF must already have been called on it.
2035 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002036void
Fred Drake100814d2000-07-09 15:48:49 +00002037_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002038{
Tim Peters803526b2002-07-07 05:13:56 +00002039 assert(PyObject_IS_GC(op));
2040 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2041 assert(op->ob_refcnt == 0);
Neil Schemenauerf589c052002-03-29 03:05:54 +00002042 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
Guido van Rossume92e6102000-04-24 15:40:53 +00002043 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002044}
2045
Tim Peters803526b2002-07-07 05:13:56 +00002046/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2047 * the call-stack unwinds again.
2048 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002049void
Fred Drake100814d2000-07-09 15:48:49 +00002050_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002051{
2052 while (_PyTrash_delete_later) {
Tim Peters803526b2002-07-07 05:13:56 +00002053 PyObject *op = _PyTrash_delete_later;
2054 destructor dealloc = op->ob_type->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002055
Neil Schemenauerf589c052002-03-29 03:05:54 +00002056 _PyTrash_delete_later =
Tim Peters803526b2002-07-07 05:13:56 +00002057 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002058
Tim Peters803526b2002-07-07 05:13:56 +00002059 /* Call the deallocator directly. This used to try to
2060 * fool Py_DECREF into calling it indirectly, but
2061 * Py_DECREF was already called on this object, and in
2062 * assorted non-release builds calling Py_DECREF again ends
2063 * up distorting allocation statistics.
2064 */
2065 assert(op->ob_refcnt == 0);
Guido van Rossumd724b232000-03-13 16:01:29 +00002066 ++_PyTrash_delete_nesting;
Tim Peters803526b2002-07-07 05:13:56 +00002067 (*dealloc)(op);
Guido van Rossumd724b232000-03-13 16:01:29 +00002068 --_PyTrash_delete_nesting;
2069 }
2070}