fix to work on python <= 2.1
[python/dscho.git] / Objects / object.c
blob93057c06946b84fe84df8eabae39fcec44c99273
2 /* Generic object operations; and implementation of None (NoObject) */
4 #include "Python.h"
6 #ifdef macintosh
7 #include "macglue.h"
8 #endif
10 #ifdef Py_REF_DEBUG
11 long _Py_RefTotal;
12 #endif
14 int Py_DivisionWarningFlag;
16 /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
17 These are used by the individual routines for object creation.
18 Do not call them otherwise, they do not initialize the object! */
20 #ifdef Py_TRACE_REFS
21 /* Head of circular doubly-linked list of all objects. These are linked
22 * together via the _ob_prev and _ob_next members of a PyObject, which
23 * exist only in a Py_TRACE_REFS build.
25 static PyObject refchain = {&refchain, &refchain};
27 /* Insert op at the front of the list of all objects. If force is true,
28 * op is added even if _ob_prev and _ob_next are non-NULL already. If
29 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
30 * force should be true if and only if op points to freshly allocated,
31 * uninitialized memory, or you've unlinked op from the list and are
32 * relinking it into the front.
33 * Note that objects are normally added to the list via _Py_NewReference,
34 * which is called by PyObject_Init. Not all objects are initialized that
35 * way, though; exceptions include statically allocated type objects, and
36 * statically allocated singletons (like Py_True and Py_None).
38 void
39 _Py_AddToAllObjects(PyObject *op, int force)
41 #ifdef Py_DEBUG
42 if (!force) {
43 /* If it's initialized memory, op must be in or out of
44 * the list unambiguously.
46 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
48 #endif
49 if (force || op->_ob_prev == NULL) {
50 op->_ob_next = refchain._ob_next;
51 op->_ob_prev = &refchain;
52 refchain._ob_next->_ob_prev = op;
53 refchain._ob_next = op;
56 #endif /* Py_TRACE_REFS */
58 #ifdef COUNT_ALLOCS
59 static PyTypeObject *type_list;
60 extern int tuple_zero_allocs, fast_tuple_allocs;
61 extern int quick_int_allocs, quick_neg_int_allocs;
62 extern int null_strings, one_strings;
63 void
64 dump_counts(void)
66 PyTypeObject *tp;
68 for (tp = type_list; tp; tp = tp->tp_next)
69 fprintf(stderr, "%s alloc'd: %d, freed: %d, max in use: %d\n",
70 tp->tp_name, tp->tp_allocs, tp->tp_frees,
71 tp->tp_maxalloc);
72 fprintf(stderr, "fast tuple allocs: %d, empty: %d\n",
73 fast_tuple_allocs, tuple_zero_allocs);
74 fprintf(stderr, "fast int allocs: pos: %d, neg: %d\n",
75 quick_int_allocs, quick_neg_int_allocs);
76 fprintf(stderr, "null strings: %d, 1-strings: %d\n",
77 null_strings, one_strings);
80 PyObject *
81 get_counts(void)
83 PyTypeObject *tp;
84 PyObject *result;
85 PyObject *v;
87 result = PyList_New(0);
88 if (result == NULL)
89 return NULL;
90 for (tp = type_list; tp; tp = tp->tp_next) {
91 v = Py_BuildValue("(siii)", tp->tp_name, tp->tp_allocs,
92 tp->tp_frees, tp->tp_maxalloc);
93 if (v == NULL) {
94 Py_DECREF(result);
95 return NULL;
97 if (PyList_Append(result, v) < 0) {
98 Py_DECREF(v);
99 Py_DECREF(result);
100 return NULL;
102 Py_DECREF(v);
104 return result;
107 void
108 inc_count(PyTypeObject *tp)
110 if (tp->tp_allocs == 0) {
111 /* first time; insert in linked list */
112 if (tp->tp_next != NULL) /* sanity check */
113 Py_FatalError("XXX inc_count sanity check");
114 tp->tp_next = type_list;
115 /* Note that as of Python 2.2, heap-allocated type objects
116 * can go away, but this code requires that they stay alive
117 * until program exit. That's why we're careful with
118 * refcounts here. type_list gets a new reference to tp,
119 * while ownership of the reference type_list used to hold
120 * (if any) was transferred to tp->tp_next in the line above.
121 * tp is thus effectively immortal after this.
123 Py_INCREF(tp);
124 type_list = tp;
125 #ifdef Py_TRACE_REFS
126 /* Also insert in the doubly-linked list of all objects,
127 * if not already there.
129 _Py_AddToAllObjects((PyObject *)tp, 0);
130 #endif
132 tp->tp_allocs++;
133 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
134 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
136 #endif
138 #ifdef Py_REF_DEBUG
139 /* Log a fatal error; doesn't return. */
140 void
141 _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
143 char buf[300];
145 PyOS_snprintf(buf, sizeof(buf),
146 "%s:%i object at %p has negative ref count %i",
147 fname, lineno, op, op->ob_refcnt);
148 Py_FatalError(buf);
151 #endif /* Py_REF_DEBUG */
153 PyObject *
154 PyObject_Init(PyObject *op, PyTypeObject *tp)
156 if (op == NULL)
157 return PyErr_NoMemory();
158 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
159 op->ob_type = tp;
160 _Py_NewReference(op);
161 return op;
164 PyVarObject *
165 PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, int size)
167 if (op == NULL)
168 return (PyVarObject *) PyErr_NoMemory();
169 /* Any changes should be reflected in PyObject_INIT_VAR */
170 op->ob_size = size;
171 op->ob_type = tp;
172 _Py_NewReference((PyObject *)op);
173 return op;
176 PyObject *
177 _PyObject_New(PyTypeObject *tp)
179 PyObject *op;
180 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
181 if (op == NULL)
182 return PyErr_NoMemory();
183 return PyObject_INIT(op, tp);
186 PyVarObject *
187 _PyObject_NewVar(PyTypeObject *tp, int nitems)
189 PyVarObject *op;
190 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
191 op = (PyVarObject *) PyObject_MALLOC(size);
192 if (op == NULL)
193 return (PyVarObject *)PyErr_NoMemory();
194 return PyObject_INIT_VAR(op, tp, nitems);
197 /* for binary compatibility with 2.2 */
198 #undef _PyObject_Del
199 void
200 _PyObject_Del(PyObject *op)
202 PyObject_FREE(op);
205 /* Implementation of PyObject_Print with recursion checking */
206 static int
207 internal_print(PyObject *op, FILE *fp, int flags, int nesting)
209 int ret = 0;
210 if (nesting > 10) {
211 PyErr_SetString(PyExc_RuntimeError, "print recursion");
212 return -1;
214 if (PyErr_CheckSignals())
215 return -1;
216 #ifdef USE_STACKCHECK
217 if (PyOS_CheckStack()) {
218 PyErr_SetString(PyExc_MemoryError, "stack overflow");
219 return -1;
221 #endif
222 clearerr(fp); /* Clear any previous error condition */
223 if (op == NULL) {
224 fprintf(fp, "<nil>");
226 else {
227 if (op->ob_refcnt <= 0)
228 fprintf(fp, "<refcnt %u at %p>",
229 op->ob_refcnt, op);
230 else if (op->ob_type->tp_print == NULL) {
231 PyObject *s;
232 if (flags & Py_PRINT_RAW)
233 s = PyObject_Str(op);
234 else
235 s = PyObject_Repr(op);
236 if (s == NULL)
237 ret = -1;
238 else {
239 ret = internal_print(s, fp, Py_PRINT_RAW,
240 nesting+1);
242 Py_XDECREF(s);
244 else
245 ret = (*op->ob_type->tp_print)(op, fp, flags);
247 if (ret == 0) {
248 if (ferror(fp)) {
249 PyErr_SetFromErrno(PyExc_IOError);
250 clearerr(fp);
251 ret = -1;
254 return ret;
258 PyObject_Print(PyObject *op, FILE *fp, int flags)
260 return internal_print(op, fp, flags, 0);
264 /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
265 void _PyObject_Dump(PyObject* op)
267 if (op == NULL)
268 fprintf(stderr, "NULL\n");
269 else {
270 fprintf(stderr, "object : ");
271 (void)PyObject_Print(op, stderr, 0);
272 fprintf(stderr, "\n"
273 "type : %s\n"
274 "refcount: %d\n"
275 "address : %p\n",
276 op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
277 op->ob_refcnt,
278 op);
282 PyObject *
283 PyObject_Repr(PyObject *v)
285 if (PyErr_CheckSignals())
286 return NULL;
287 #ifdef USE_STACKCHECK
288 if (PyOS_CheckStack()) {
289 PyErr_SetString(PyExc_MemoryError, "stack overflow");
290 return NULL;
292 #endif
293 if (v == NULL)
294 return PyString_FromString("<NULL>");
295 else if (v->ob_type->tp_repr == NULL)
296 return PyString_FromFormat("<%s object at %p>",
297 v->ob_type->tp_name, v);
298 else {
299 PyObject *res;
300 res = (*v->ob_type->tp_repr)(v);
301 if (res == NULL)
302 return NULL;
303 #ifdef Py_USING_UNICODE
304 if (PyUnicode_Check(res)) {
305 PyObject* str;
306 str = PyUnicode_AsUnicodeEscapeString(res);
307 Py_DECREF(res);
308 if (str)
309 res = str;
310 else
311 return NULL;
313 #endif
314 if (!PyString_Check(res)) {
315 PyErr_Format(PyExc_TypeError,
316 "__repr__ returned non-string (type %.200s)",
317 res->ob_type->tp_name);
318 Py_DECREF(res);
319 return NULL;
321 return res;
325 PyObject *
326 PyObject_Str(PyObject *v)
328 PyObject *res;
330 if (v == NULL)
331 return PyString_FromString("<NULL>");
332 if (PyString_CheckExact(v)) {
333 Py_INCREF(v);
334 return v;
336 if (v->ob_type->tp_str == NULL)
337 return PyObject_Repr(v);
339 res = (*v->ob_type->tp_str)(v);
340 if (res == NULL)
341 return NULL;
342 #ifdef Py_USING_UNICODE
343 if (PyUnicode_Check(res)) {
344 PyObject* str;
345 str = PyUnicode_AsEncodedString(res, NULL, NULL);
346 Py_DECREF(res);
347 if (str)
348 res = str;
349 else
350 return NULL;
352 #endif
353 if (!PyString_Check(res)) {
354 PyErr_Format(PyExc_TypeError,
355 "__str__ returned non-string (type %.200s)",
356 res->ob_type->tp_name);
357 Py_DECREF(res);
358 return NULL;
360 return res;
363 #ifdef Py_USING_UNICODE
364 PyObject *
365 PyObject_Unicode(PyObject *v)
367 PyObject *res;
369 if (v == NULL)
370 res = PyString_FromString("<NULL>");
371 if (PyUnicode_CheckExact(v)) {
372 Py_INCREF(v);
373 return v;
375 if (PyUnicode_Check(v)) {
376 /* For a Unicode subtype that's not a Unicode object,
377 return a true Unicode object with the same data. */
378 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
379 PyUnicode_GET_SIZE(v));
381 if (PyString_Check(v)) {
382 Py_INCREF(v);
383 res = v;
385 else {
386 PyObject *func;
387 static PyObject *unicodestr;
388 /* XXX As soon as we have a tp_unicode slot, we should
389 check this before trying the __unicode__
390 method. */
391 if (unicodestr == NULL) {
392 unicodestr= PyString_InternFromString(
393 "__unicode__");
394 if (unicodestr == NULL)
395 return NULL;
397 func = PyObject_GetAttr(v, unicodestr);
398 if (func != NULL) {
399 res = PyEval_CallObject(func, (PyObject *)NULL);
400 Py_DECREF(func);
402 else {
403 PyErr_Clear();
404 if (v->ob_type->tp_str != NULL)
405 res = (*v->ob_type->tp_str)(v);
406 else
407 res = PyObject_Repr(v);
410 if (res == NULL)
411 return NULL;
412 if (!PyUnicode_Check(res)) {
413 PyObject *str;
414 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
415 Py_DECREF(res);
416 if (str)
417 res = str;
418 else
419 return NULL;
421 return res;
423 #endif
426 /* Helper to warn about deprecated tp_compare return values. Return:
427 -2 for an exception;
428 -1 if v < w;
429 0 if v == w;
430 1 if v > w.
431 (This function cannot return 2.)
433 static int
434 adjust_tp_compare(int c)
436 if (PyErr_Occurred()) {
437 if (c != -1 && c != -2) {
438 PyObject *t, *v, *tb;
439 PyErr_Fetch(&t, &v, &tb);
440 if (PyErr_Warn(PyExc_RuntimeWarning,
441 "tp_compare didn't return -1 or -2 "
442 "for exception") < 0) {
443 Py_XDECREF(t);
444 Py_XDECREF(v);
445 Py_XDECREF(tb);
447 else
448 PyErr_Restore(t, v, tb);
450 return -2;
452 else if (c < -1 || c > 1) {
453 if (PyErr_Warn(PyExc_RuntimeWarning,
454 "tp_compare didn't return -1, 0 or 1") < 0)
455 return -2;
456 else
457 return c < -1 ? -1 : 1;
459 else {
460 assert(c >= -1 && c <= 1);
461 return c;
466 /* Macro to get the tp_richcompare field of a type if defined */
467 #define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
468 ? (t)->tp_richcompare : NULL)
470 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
471 static int swapped_op[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
473 /* Try a genuine rich comparison, returning an object. Return:
474 NULL for exception;
475 NotImplemented if this particular rich comparison is not implemented or
476 undefined;
477 some object not equal to NotImplemented if it is implemented
478 (this latter object may not be a Boolean).
480 static PyObject *
481 try_rich_compare(PyObject *v, PyObject *w, int op)
483 richcmpfunc f;
484 PyObject *res;
486 if (v->ob_type != w->ob_type &&
487 PyType_IsSubtype(w->ob_type, v->ob_type) &&
488 (f = RICHCOMPARE(w->ob_type)) != NULL) {
489 res = (*f)(w, v, swapped_op[op]);
490 if (res != Py_NotImplemented)
491 return res;
492 Py_DECREF(res);
494 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
495 res = (*f)(v, w, op);
496 if (res != Py_NotImplemented)
497 return res;
498 Py_DECREF(res);
500 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
501 return (*f)(w, v, swapped_op[op]);
503 res = Py_NotImplemented;
504 Py_INCREF(res);
505 return res;
508 /* Try a genuine rich comparison, returning an int. Return:
509 -1 for exception (including the case where try_rich_compare() returns an
510 object that's not a Boolean);
511 0 if the outcome is false;
512 1 if the outcome is true;
513 2 if this particular rich comparison is not implemented or undefined.
515 static int
516 try_rich_compare_bool(PyObject *v, PyObject *w, int op)
518 PyObject *res;
519 int ok;
521 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
522 return 2; /* Shortcut, avoid INCREF+DECREF */
523 res = try_rich_compare(v, w, op);
524 if (res == NULL)
525 return -1;
526 if (res == Py_NotImplemented) {
527 Py_DECREF(res);
528 return 2;
530 ok = PyObject_IsTrue(res);
531 Py_DECREF(res);
532 return ok;
535 /* Try rich comparisons to determine a 3-way comparison. Return:
536 -2 for an exception;
537 -1 if v < w;
538 0 if v == w;
539 1 if v > w;
540 2 if this particular rich comparison is not implemented or undefined.
542 static int
543 try_rich_to_3way_compare(PyObject *v, PyObject *w)
545 static struct { int op; int outcome; } tries[3] = {
546 /* Try this operator, and if it is true, use this outcome: */
547 {Py_EQ, 0},
548 {Py_LT, -1},
549 {Py_GT, 1},
551 int i;
553 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
554 return 2; /* Shortcut */
556 for (i = 0; i < 3; i++) {
557 switch (try_rich_compare_bool(v, w, tries[i].op)) {
558 case -1:
559 return -2;
560 case 1:
561 return tries[i].outcome;
565 return 2;
568 /* Try a 3-way comparison, returning an int. Return:
569 -2 for an exception;
570 -1 if v < w;
571 0 if v == w;
572 1 if v > w;
573 2 if this particular 3-way comparison is not implemented or undefined.
575 static int
576 try_3way_compare(PyObject *v, PyObject *w)
578 int c;
579 cmpfunc f;
581 /* Comparisons involving instances are given to instance_compare,
582 which has the same return conventions as this function. */
584 f = v->ob_type->tp_compare;
585 if (PyInstance_Check(v))
586 return (*f)(v, w);
587 if (PyInstance_Check(w))
588 return (*w->ob_type->tp_compare)(v, w);
590 /* If both have the same (non-NULL) tp_compare, use it. */
591 if (f != NULL && f == w->ob_type->tp_compare) {
592 c = (*f)(v, w);
593 return adjust_tp_compare(c);
596 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
597 if (f == _PyObject_SlotCompare ||
598 w->ob_type->tp_compare == _PyObject_SlotCompare)
599 return _PyObject_SlotCompare(v, w);
601 /* Try coercion; if it fails, give up */
602 c = PyNumber_CoerceEx(&v, &w);
603 if (c < 0)
604 return -2;
605 if (c > 0)
606 return 2;
608 /* Try v's comparison, if defined */
609 if ((f = v->ob_type->tp_compare) != NULL) {
610 c = (*f)(v, w);
611 Py_DECREF(v);
612 Py_DECREF(w);
613 return adjust_tp_compare(c);
616 /* Try w's comparison, if defined */
617 if ((f = w->ob_type->tp_compare) != NULL) {
618 c = (*f)(w, v); /* swapped! */
619 Py_DECREF(v);
620 Py_DECREF(w);
621 c = adjust_tp_compare(c);
622 if (c >= -1)
623 return -c; /* Swapped! */
624 else
625 return c;
628 /* No comparison defined */
629 Py_DECREF(v);
630 Py_DECREF(w);
631 return 2;
634 /* Final fallback 3-way comparison, returning an int. Return:
635 -2 if an error occurred;
636 -1 if v < w;
637 0 if v == w;
638 1 if v > w.
640 static int
641 default_3way_compare(PyObject *v, PyObject *w)
643 int c;
644 char *vname, *wname;
646 if (v->ob_type == w->ob_type) {
647 /* When comparing these pointers, they must be cast to
648 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
649 * uintptr_t). ANSI specifies that pointer compares other
650 * than == and != to non-related structures are undefined.
652 Py_uintptr_t vv = (Py_uintptr_t)v;
653 Py_uintptr_t ww = (Py_uintptr_t)w;
654 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
657 #ifdef Py_USING_UNICODE
658 /* Special case for Unicode */
659 if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
660 c = PyUnicode_Compare(v, w);
661 if (!PyErr_Occurred())
662 return c;
663 /* TypeErrors are ignored: if Unicode coercion fails due
664 to one of the arguments not having the right type, we
665 continue as defined by the coercion protocol (see
666 above). Luckily, decoding errors are reported as
667 ValueErrors and are not masked by this technique. */
668 if (!PyErr_ExceptionMatches(PyExc_TypeError))
669 return -2;
670 PyErr_Clear();
672 #endif
674 /* None is smaller than anything */
675 if (v == Py_None)
676 return -1;
677 if (w == Py_None)
678 return 1;
680 /* different type: compare type names; numbers are smaller */
681 if (PyNumber_Check(v))
682 vname = "";
683 else
684 vname = v->ob_type->tp_name;
685 if (PyNumber_Check(w))
686 wname = "";
687 else
688 wname = w->ob_type->tp_name;
689 c = strcmp(vname, wname);
690 if (c < 0)
691 return -1;
692 if (c > 0)
693 return 1;
694 /* Same type name, or (more likely) incomparable numeric types */
695 return ((Py_uintptr_t)(v->ob_type) < (
696 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
699 #define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
701 /* Do a 3-way comparison, by hook or by crook. Return:
702 -2 for an exception (but see below);
703 -1 if v < w;
704 0 if v == w;
705 1 if v > w;
706 BUT: if the object implements a tp_compare function, it returns
707 whatever this function returns (whether with an exception or not).
709 static int
710 do_cmp(PyObject *v, PyObject *w)
712 int c;
713 cmpfunc f;
715 if (v->ob_type == w->ob_type
716 && (f = v->ob_type->tp_compare) != NULL) {
717 c = (*f)(v, w);
718 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;
723 /* Else fall through to try_rich_to_3way_compare() */
725 else
726 return adjust_tp_compare(c);
728 /* 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
734 c = try_rich_to_3way_compare(v, w);
735 if (c < 2)
736 return c;
737 c = try_3way_compare(v, w);
738 if (c < 2)
739 return c;
740 return default_3way_compare(v, w);
743 /* compare_nesting is incremented before calling compare (for
744 some types) and decremented on exit. If the count exceeds the
745 nesting limit, enable code to detect circular data structures.
747 This is a tunable parameter that should only affect the performance
748 of comparisons, nothing else. Setting it high makes comparing deeply
749 nested non-cyclical data structures faster, but makes comparing cyclical
750 data structures slower.
752 #define NESTING_LIMIT 20
754 static int compare_nesting = 0;
756 static PyObject*
757 get_inprogress_dict(void)
759 static PyObject *key;
760 PyObject *tstate_dict, *inprogress;
762 if (key == NULL) {
763 key = PyString_InternFromString("cmp_state");
764 if (key == NULL)
765 return NULL;
768 tstate_dict = PyThreadState_GetDict();
769 if (tstate_dict == NULL) {
770 PyErr_BadInternalCall();
771 return NULL;
774 inprogress = PyDict_GetItem(tstate_dict, key);
775 if (inprogress == NULL) {
776 inprogress = PyDict_New();
777 if (inprogress == NULL)
778 return NULL;
779 if (PyDict_SetItem(tstate_dict, key, inprogress) == -1) {
780 Py_DECREF(inprogress);
781 return NULL;
783 Py_DECREF(inprogress);
786 return inprogress;
789 /* If the comparison "v op w" is already in progress in this thread, returns
790 * a borrowed reference to Py_None (the caller must not decref).
791 * If it's not already in progress, returns "a token" which must eventually
792 * be passed to delete_token(). The caller must not decref this either
793 * (delete_token decrefs it). The token must not survive beyond any point
794 * where v or w may die.
795 * If an error occurs (out-of-memory), returns NULL.
797 static PyObject *
798 check_recursion(PyObject *v, PyObject *w, int op)
800 PyObject *inprogress;
801 PyObject *token;
802 Py_uintptr_t iv = (Py_uintptr_t)v;
803 Py_uintptr_t iw = (Py_uintptr_t)w;
804 PyObject *x, *y, *z;
806 inprogress = get_inprogress_dict();
807 if (inprogress == NULL)
808 return NULL;
810 token = PyTuple_New(3);
811 if (token == NULL)
812 return NULL;
814 if (iv <= iw) {
815 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)v));
816 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)w));
817 if (op >= 0)
818 op = swapped_op[op];
819 } else {
820 PyTuple_SET_ITEM(token, 0, x = PyLong_FromVoidPtr((void *)w));
821 PyTuple_SET_ITEM(token, 1, y = PyLong_FromVoidPtr((void *)v));
823 PyTuple_SET_ITEM(token, 2, z = PyInt_FromLong((long)op));
824 if (x == NULL || y == NULL || z == NULL) {
825 Py_DECREF(token);
826 return NULL;
829 if (PyDict_GetItem(inprogress, token) != NULL) {
830 Py_DECREF(token);
831 return Py_None; /* Without INCREF! */
834 if (PyDict_SetItem(inprogress, token, token) < 0) {
835 Py_DECREF(token);
836 return NULL;
839 return token;
842 static void
843 delete_token(PyObject *token)
845 PyObject *inprogress;
847 if (token == NULL || token == Py_None)
848 return;
849 inprogress = get_inprogress_dict();
850 if (inprogress == NULL)
851 PyErr_Clear();
852 else
853 PyDict_DelItem(inprogress, token);
854 Py_DECREF(token);
857 /* Compare v to w. Return
858 -1 if v < w or exception (PyErr_Occurred() true in latter case).
859 0 if v == w.
860 1 if v > w.
861 XXX The docs (C API manual) say the return value is undefined in case
862 XXX of error.
865 PyObject_Compare(PyObject *v, PyObject *w)
867 PyTypeObject *vtp;
868 int result;
870 #if defined(USE_STACKCHECK)
871 if (PyOS_CheckStack()) {
872 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
873 return -1;
875 #endif
876 if (v == NULL || w == NULL) {
877 PyErr_BadInternalCall();
878 return -1;
880 if (v == w)
881 return 0;
882 vtp = v->ob_type;
883 compare_nesting++;
884 if (compare_nesting > NESTING_LIMIT &&
885 (vtp->tp_as_mapping || vtp->tp_as_sequence) &&
886 !PyString_CheckExact(v) &&
887 !PyTuple_CheckExact(v)) {
888 /* try to detect circular data structures */
889 PyObject *token = check_recursion(v, w, -1);
891 if (token == NULL) {
892 result = -1;
894 else if (token == Py_None) {
895 /* already comparing these objects. assume
896 they're equal until shown otherwise */
897 result = 0;
899 else {
900 result = do_cmp(v, w);
901 delete_token(token);
904 else {
905 result = do_cmp(v, w);
907 compare_nesting--;
908 return result < 0 ? -1 : result;
911 /* Return (new reference to) Py_True or Py_False. */
912 static PyObject *
913 convert_3way_to_object(int op, int c)
915 PyObject *result;
916 switch (op) {
917 case Py_LT: c = c < 0; break;
918 case Py_LE: c = c <= 0; break;
919 case Py_EQ: c = c == 0; break;
920 case Py_NE: c = c != 0; break;
921 case Py_GT: c = c > 0; break;
922 case Py_GE: c = c >= 0; break;
924 result = c ? Py_True : Py_False;
925 Py_INCREF(result);
926 return result;
929 /* We want a rich comparison but don't have one. Try a 3-way cmp instead.
930 Return
931 NULL if error
932 Py_True if v op w
933 Py_False if not (v op w)
935 static PyObject *
936 try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
938 int c;
940 c = try_3way_compare(v, w);
941 if (c >= 2)
942 c = default_3way_compare(v, w);
943 if (c <= -2)
944 return NULL;
945 return convert_3way_to_object(op, c);
948 /* Do rich comparison on v and w. Return
949 NULL if error
950 Else a new reference to an object other than Py_NotImplemented, usually(?):
951 Py_True if v op w
952 Py_False if not (v op w)
954 static PyObject *
955 do_richcmp(PyObject *v, PyObject *w, int op)
957 PyObject *res;
959 res = try_rich_compare(v, w, op);
960 if (res != Py_NotImplemented)
961 return res;
962 Py_DECREF(res);
964 return try_3way_to_rich_compare(v, w, op);
967 /* Return:
968 NULL for exception;
969 some object not equal to NotImplemented if it is implemented
970 (this latter object may not be a Boolean).
972 PyObject *
973 PyObject_RichCompare(PyObject *v, PyObject *w, int op)
975 PyObject *res;
977 assert(Py_LT <= op && op <= Py_GE);
979 compare_nesting++;
980 if (compare_nesting > NESTING_LIMIT &&
981 (v->ob_type->tp_as_mapping || v->ob_type->tp_as_sequence) &&
982 !PyString_CheckExact(v) &&
983 !PyTuple_CheckExact(v)) {
984 /* try to detect circular data structures */
985 PyObject *token = check_recursion(v, w, op);
986 if (token == NULL) {
987 res = NULL;
988 goto Done;
990 else if (token == Py_None) {
991 /* already comparing these objects with this operator.
992 assume they're equal until shown otherwise */
993 if (op == Py_EQ)
994 res = Py_True;
995 else if (op == Py_NE)
996 res = Py_False;
997 else {
998 PyErr_SetString(PyExc_ValueError,
999 "can't order recursive values");
1000 res = NULL;
1002 Py_XINCREF(res);
1004 else {
1005 res = do_richcmp(v, w, op);
1006 delete_token(token);
1008 goto Done;
1011 /* No nesting extremism.
1012 If the types are equal, and not old-style instances, try to
1013 get out cheap (don't bother with coercions etc.). */
1014 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
1015 cmpfunc fcmp;
1016 richcmpfunc frich = RICHCOMPARE(v->ob_type);
1017 /* If the type has richcmp, try it first. try_rich_compare
1018 tries it two-sided, which is not needed since we've a
1019 single type only. */
1020 if (frich != NULL) {
1021 res = (*frich)(v, w, op);
1022 if (res != Py_NotImplemented)
1023 goto Done;
1024 Py_DECREF(res);
1026 /* No richcmp, or this particular richmp not implemented.
1027 Try 3-way cmp. */
1028 fcmp = v->ob_type->tp_compare;
1029 if (fcmp != NULL) {
1030 int c = (*fcmp)(v, w);
1031 c = adjust_tp_compare(c);
1032 if (c == -2) {
1033 res = NULL;
1034 goto Done;
1036 res = convert_3way_to_object(op, c);
1037 goto Done;
1041 /* Fast path not taken, or couldn't deliver a useful result. */
1042 res = do_richcmp(v, w, op);
1043 Done:
1044 compare_nesting--;
1045 return res;
1048 /* Return -1 if error; 1 if v op w; 0 if not (v op w). */
1050 PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
1052 PyObject *res = PyObject_RichCompare(v, w, op);
1053 int ok;
1055 if (res == NULL)
1056 return -1;
1057 if (PyBool_Check(res))
1058 ok = (res == Py_True);
1059 else
1060 ok = PyObject_IsTrue(res);
1061 Py_DECREF(res);
1062 return ok;
1065 /* Set of hash utility functions to help maintaining the invariant that
1066 iff a==b then hash(a)==hash(b)
1068 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1071 long
1072 _Py_HashDouble(double v)
1074 double intpart, fractpart;
1075 int expo;
1076 long hipart;
1077 long x; /* the final hash value */
1078 /* This is designed so that Python numbers of different types
1079 * that compare equal hash to the same value; otherwise comparisons
1080 * of mapping keys will turn out weird.
1083 #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1085 extended e;
1086 fractpart = modf(v, &e);
1087 intpart = e;
1089 #else
1090 fractpart = modf(v, &intpart);
1091 #endif
1092 if (fractpart == 0.0) {
1093 /* This must return the same hash as an equal int or long. */
1094 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1095 /* Convert to long and use its hash. */
1096 PyObject *plong; /* converted to Python long */
1097 if (Py_IS_INFINITY(intpart))
1098 /* can't convert to long int -- arbitrary */
1099 v = v < 0 ? -271828.0 : 314159.0;
1100 plong = PyLong_FromDouble(v);
1101 if (plong == NULL)
1102 return -1;
1103 x = PyObject_Hash(plong);
1104 Py_DECREF(plong);
1105 return x;
1107 /* Fits in a C long == a Python int, so is its own hash. */
1108 x = (long)intpart;
1109 if (x == -1)
1110 x = -2;
1111 return x;
1113 /* The fractional part is non-zero, so we don't have to worry about
1114 * making this match the hash of some other type.
1115 * Use frexp to get at the bits in the double.
1116 * Since the VAX D double format has 56 mantissa bits, which is the
1117 * most of any double format in use, each of these parts may have as
1118 * many as (but no more than) 56 significant bits.
1119 * So, assuming sizeof(long) >= 4, each part can be broken into two
1120 * longs; frexp and multiplication are used to do that.
1121 * Also, since the Cray double format has 15 exponent bits, which is
1122 * the most of any double format in use, shifting the exponent field
1123 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
1125 v = frexp(v, &expo);
1126 v *= 2147483648.0; /* 2**31 */
1127 hipart = (long)v; /* take the top 32 bits */
1128 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1129 x = hipart + (long)v + (expo << 15);
1130 if (x == -1)
1131 x = -2;
1132 return x;
1135 long
1136 _Py_HashPointer(void *p)
1138 #if SIZEOF_LONG >= SIZEOF_VOID_P
1139 return (long)p;
1140 #else
1141 /* convert to a Python long and hash that */
1142 PyObject* longobj;
1143 long x;
1145 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1146 x = -1;
1147 goto finally;
1149 x = PyObject_Hash(longobj);
1151 finally:
1152 Py_XDECREF(longobj);
1153 return x;
1154 #endif
1158 long
1159 PyObject_Hash(PyObject *v)
1161 PyTypeObject *tp = v->ob_type;
1162 if (tp->tp_hash != NULL)
1163 return (*tp->tp_hash)(v);
1164 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
1165 return _Py_HashPointer(v); /* Use address as hash value */
1167 /* If there's a cmp but no hash defined, the object can't be hashed */
1168 PyErr_SetString(PyExc_TypeError, "unhashable type");
1169 return -1;
1172 PyObject *
1173 PyObject_GetAttrString(PyObject *v, char *name)
1175 PyObject *w, *res;
1177 if (v->ob_type->tp_getattr != NULL)
1178 return (*v->ob_type->tp_getattr)(v, name);
1179 w = PyString_InternFromString(name);
1180 if (w == NULL)
1181 return NULL;
1182 res = PyObject_GetAttr(v, w);
1183 Py_XDECREF(w);
1184 return res;
1188 PyObject_HasAttrString(PyObject *v, char *name)
1190 PyObject *res = PyObject_GetAttrString(v, name);
1191 if (res != NULL) {
1192 Py_DECREF(res);
1193 return 1;
1195 PyErr_Clear();
1196 return 0;
1200 PyObject_SetAttrString(PyObject *v, char *name, PyObject *w)
1202 PyObject *s;
1203 int res;
1205 if (v->ob_type->tp_setattr != NULL)
1206 return (*v->ob_type->tp_setattr)(v, name, w);
1207 s = PyString_InternFromString(name);
1208 if (s == NULL)
1209 return -1;
1210 res = PyObject_SetAttr(v, s, w);
1211 Py_XDECREF(s);
1212 return res;
1215 PyObject *
1216 PyObject_GetAttr(PyObject *v, PyObject *name)
1218 PyTypeObject *tp = v->ob_type;
1220 if (!PyString_Check(name)) {
1221 #ifdef Py_USING_UNICODE
1222 /* The Unicode to string conversion is done here because the
1223 existing tp_getattro slots expect a string object as name
1224 and we wouldn't want to break those. */
1225 if (PyUnicode_Check(name)) {
1226 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1227 if (name == NULL)
1228 return NULL;
1230 else
1231 #endif
1233 PyErr_SetString(PyExc_TypeError,
1234 "attribute name must be string");
1235 return NULL;
1238 if (tp->tp_getattro != NULL)
1239 return (*tp->tp_getattro)(v, name);
1240 if (tp->tp_getattr != NULL)
1241 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1242 PyErr_Format(PyExc_AttributeError,
1243 "'%.50s' object has no attribute '%.400s'",
1244 tp->tp_name, PyString_AS_STRING(name));
1245 return NULL;
1249 PyObject_HasAttr(PyObject *v, PyObject *name)
1251 PyObject *res = PyObject_GetAttr(v, name);
1252 if (res != NULL) {
1253 Py_DECREF(res);
1254 return 1;
1256 PyErr_Clear();
1257 return 0;
1261 PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
1263 PyTypeObject *tp = v->ob_type;
1264 int err;
1266 if (!PyString_Check(name)){
1267 #ifdef Py_USING_UNICODE
1268 /* The Unicode to string conversion is done here because the
1269 existing tp_setattro slots expect a string object as name
1270 and we wouldn't want to break those. */
1271 if (PyUnicode_Check(name)) {
1272 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1273 if (name == NULL)
1274 return -1;
1276 else
1277 #endif
1279 PyErr_SetString(PyExc_TypeError,
1280 "attribute name must be string");
1281 return -1;
1284 else
1285 Py_INCREF(name);
1287 PyString_InternInPlace(&name);
1288 if (tp->tp_setattro != NULL) {
1289 err = (*tp->tp_setattro)(v, name, value);
1290 Py_DECREF(name);
1291 return err;
1293 if (tp->tp_setattr != NULL) {
1294 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1295 Py_DECREF(name);
1296 return err;
1298 Py_DECREF(name);
1299 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1300 PyErr_Format(PyExc_TypeError,
1301 "'%.100s' object has no attributes "
1302 "(%s .%.100s)",
1303 tp->tp_name,
1304 value==NULL ? "del" : "assign to",
1305 PyString_AS_STRING(name));
1306 else
1307 PyErr_Format(PyExc_TypeError,
1308 "'%.100s' object has only read-only attributes "
1309 "(%s .%.100s)",
1310 tp->tp_name,
1311 value==NULL ? "del" : "assign to",
1312 PyString_AS_STRING(name));
1313 return -1;
1316 /* Helper to get a pointer to an object's __dict__ slot, if any */
1318 PyObject **
1319 _PyObject_GetDictPtr(PyObject *obj)
1321 long dictoffset;
1322 PyTypeObject *tp = obj->ob_type;
1324 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1325 return NULL;
1326 dictoffset = tp->tp_dictoffset;
1327 if (dictoffset == 0)
1328 return NULL;
1329 if (dictoffset < 0) {
1330 int tsize;
1331 size_t size;
1333 tsize = ((PyVarObject *)obj)->ob_size;
1334 if (tsize < 0)
1335 tsize = -tsize;
1336 size = _PyObject_VAR_SIZE(tp, tsize);
1338 dictoffset += (long)size;
1339 assert(dictoffset > 0);
1340 assert(dictoffset % SIZEOF_VOID_P == 0);
1342 return (PyObject **) ((char *)obj + dictoffset);
1345 /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1347 PyObject *
1348 PyObject_SelfIter(PyObject *obj)
1350 Py_INCREF(obj);
1351 return obj;
1354 PyObject *
1355 PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1357 PyTypeObject *tp = obj->ob_type;
1358 PyObject *descr = NULL;
1359 PyObject *res = NULL;
1360 descrgetfunc f;
1361 long dictoffset;
1362 PyObject **dictptr;
1364 if (!PyString_Check(name)){
1365 #ifdef Py_USING_UNICODE
1366 /* The Unicode to string conversion is done here because the
1367 existing tp_setattro slots expect a string object as name
1368 and we wouldn't want to break those. */
1369 if (PyUnicode_Check(name)) {
1370 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1371 if (name == NULL)
1372 return NULL;
1374 else
1375 #endif
1377 PyErr_SetString(PyExc_TypeError,
1378 "attribute name must be string");
1379 return NULL;
1382 else
1383 Py_INCREF(name);
1385 if (tp->tp_dict == NULL) {
1386 if (PyType_Ready(tp) < 0)
1387 goto done;
1390 /* Inline _PyType_Lookup */
1392 int i, n;
1393 PyObject *mro, *base, *dict;
1395 /* Look in tp_dict of types in MRO */
1396 mro = tp->tp_mro;
1397 assert(mro != NULL);
1398 assert(PyTuple_Check(mro));
1399 n = PyTuple_GET_SIZE(mro);
1400 for (i = 0; i < n; i++) {
1401 base = PyTuple_GET_ITEM(mro, i);
1402 if (PyClass_Check(base))
1403 dict = ((PyClassObject *)base)->cl_dict;
1404 else {
1405 assert(PyType_Check(base));
1406 dict = ((PyTypeObject *)base)->tp_dict;
1408 assert(dict && PyDict_Check(dict));
1409 descr = PyDict_GetItem(dict, name);
1410 if (descr != NULL)
1411 break;
1415 f = NULL;
1416 if (descr != NULL &&
1417 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1418 f = descr->ob_type->tp_descr_get;
1419 if (f != NULL && PyDescr_IsData(descr)) {
1420 res = f(descr, obj, (PyObject *)obj->ob_type);
1421 goto done;
1425 /* Inline _PyObject_GetDictPtr */
1426 dictoffset = tp->tp_dictoffset;
1427 if (dictoffset != 0) {
1428 PyObject *dict;
1429 if (dictoffset < 0) {
1430 int tsize;
1431 size_t size;
1433 tsize = ((PyVarObject *)obj)->ob_size;
1434 if (tsize < 0)
1435 tsize = -tsize;
1436 size = _PyObject_VAR_SIZE(tp, tsize);
1438 dictoffset += (long)size;
1439 assert(dictoffset > 0);
1440 assert(dictoffset % SIZEOF_VOID_P == 0);
1442 dictptr = (PyObject **) ((char *)obj + dictoffset);
1443 dict = *dictptr;
1444 if (dict != NULL) {
1445 res = PyDict_GetItem(dict, name);
1446 if (res != NULL) {
1447 Py_INCREF(res);
1448 goto done;
1453 if (f != NULL) {
1454 res = f(descr, obj, (PyObject *)obj->ob_type);
1455 goto done;
1458 if (descr != NULL) {
1459 Py_INCREF(descr);
1460 res = descr;
1461 goto done;
1464 PyErr_Format(PyExc_AttributeError,
1465 "'%.50s' object has no attribute '%.400s'",
1466 tp->tp_name, PyString_AS_STRING(name));
1467 done:
1468 Py_DECREF(name);
1469 return res;
1473 PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1475 PyTypeObject *tp = obj->ob_type;
1476 PyObject *descr;
1477 descrsetfunc f;
1478 PyObject **dictptr;
1479 int res = -1;
1481 if (!PyString_Check(name)){
1482 #ifdef Py_USING_UNICODE
1483 /* The Unicode to string conversion is done here because the
1484 existing tp_setattro slots expect a string object as name
1485 and we wouldn't want to break those. */
1486 if (PyUnicode_Check(name)) {
1487 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1488 if (name == NULL)
1489 return -1;
1491 else
1492 #endif
1494 PyErr_SetString(PyExc_TypeError,
1495 "attribute name must be string");
1496 return -1;
1499 else
1500 Py_INCREF(name);
1502 if (tp->tp_dict == NULL) {
1503 if (PyType_Ready(tp) < 0)
1504 goto done;
1507 descr = _PyType_Lookup(tp, name);
1508 f = NULL;
1509 if (descr != NULL &&
1510 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1511 f = descr->ob_type->tp_descr_set;
1512 if (f != NULL && PyDescr_IsData(descr)) {
1513 res = f(descr, obj, value);
1514 goto done;
1518 dictptr = _PyObject_GetDictPtr(obj);
1519 if (dictptr != NULL) {
1520 PyObject *dict = *dictptr;
1521 if (dict == NULL && value != NULL) {
1522 dict = PyDict_New();
1523 if (dict == NULL)
1524 goto done;
1525 *dictptr = dict;
1527 if (dict != NULL) {
1528 if (value == NULL)
1529 res = PyDict_DelItem(dict, name);
1530 else
1531 res = PyDict_SetItem(dict, name, value);
1532 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1533 PyErr_SetObject(PyExc_AttributeError, name);
1534 goto done;
1538 if (f != NULL) {
1539 res = f(descr, obj, value);
1540 goto done;
1543 if (descr == NULL) {
1544 PyErr_Format(PyExc_AttributeError,
1545 "'%.50s' object has no attribute '%.400s'",
1546 tp->tp_name, PyString_AS_STRING(name));
1547 goto done;
1550 PyErr_Format(PyExc_AttributeError,
1551 "'%.50s' object attribute '%.400s' is read-only",
1552 tp->tp_name, PyString_AS_STRING(name));
1553 done:
1554 Py_DECREF(name);
1555 return res;
1558 /* Test a value used as condition, e.g., in a for or if statement.
1559 Return -1 if an error occurred */
1562 PyObject_IsTrue(PyObject *v)
1564 int res;
1565 if (v == Py_True)
1566 return 1;
1567 if (v == Py_False)
1568 return 0;
1569 if (v == Py_None)
1570 return 0;
1571 else if (v->ob_type->tp_as_number != NULL &&
1572 v->ob_type->tp_as_number->nb_nonzero != NULL)
1573 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
1574 else if (v->ob_type->tp_as_mapping != NULL &&
1575 v->ob_type->tp_as_mapping->mp_length != NULL)
1576 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1577 else if (v->ob_type->tp_as_sequence != NULL &&
1578 v->ob_type->tp_as_sequence->sq_length != NULL)
1579 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1580 else
1581 return 1;
1582 return (res > 0) ? 1 : res;
1585 /* equivalent of 'not v'
1586 Return -1 if an error occurred */
1589 PyObject_Not(PyObject *v)
1591 int res;
1592 res = PyObject_IsTrue(v);
1593 if (res < 0)
1594 return res;
1595 return res == 0;
1598 /* Coerce two numeric types to the "larger" one.
1599 Increment the reference count on each argument.
1600 Return value:
1601 -1 if an error occurred;
1602 0 if the coercion succeeded (and then the reference counts are increased);
1603 1 if no coercion is possible (and no error is raised).
1606 PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
1608 register PyObject *v = *pv;
1609 register PyObject *w = *pw;
1610 int res;
1612 /* Shortcut only for old-style types */
1613 if (v->ob_type == w->ob_type &&
1614 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1616 Py_INCREF(v);
1617 Py_INCREF(w);
1618 return 0;
1620 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1621 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1622 if (res <= 0)
1623 return res;
1625 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1626 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1627 if (res <= 0)
1628 return res;
1630 return 1;
1633 /* Coerce two numeric types to the "larger" one.
1634 Increment the reference count on each argument.
1635 Return -1 and raise an exception if no coercion is possible
1636 (and then no reference count is incremented).
1639 PyNumber_Coerce(PyObject **pv, PyObject **pw)
1641 int err = PyNumber_CoerceEx(pv, pw);
1642 if (err <= 0)
1643 return err;
1644 PyErr_SetString(PyExc_TypeError, "number coercion failed");
1645 return -1;
1649 /* Test whether an object can be called */
1652 PyCallable_Check(PyObject *x)
1654 if (x == NULL)
1655 return 0;
1656 if (PyInstance_Check(x)) {
1657 PyObject *call = PyObject_GetAttrString(x, "__call__");
1658 if (call == NULL) {
1659 PyErr_Clear();
1660 return 0;
1662 /* Could test recursively but don't, for fear of endless
1663 recursion if some joker sets self.__call__ = self */
1664 Py_DECREF(call);
1665 return 1;
1667 else {
1668 return x->ob_type->tp_call != NULL;
1672 /* Helper for PyObject_Dir.
1673 Merge the __dict__ of aclass into dict, and recursively also all
1674 the __dict__s of aclass's base classes. The order of merging isn't
1675 defined, as it's expected that only the final set of dict keys is
1676 interesting.
1677 Return 0 on success, -1 on error.
1680 static int
1681 merge_class_dict(PyObject* dict, PyObject* aclass)
1683 PyObject *classdict;
1684 PyObject *bases;
1686 assert(PyDict_Check(dict));
1687 assert(aclass);
1689 /* Merge in the type's dict (if any). */
1690 classdict = PyObject_GetAttrString(aclass, "__dict__");
1691 if (classdict == NULL)
1692 PyErr_Clear();
1693 else {
1694 int status = PyDict_Update(dict, classdict);
1695 Py_DECREF(classdict);
1696 if (status < 0)
1697 return -1;
1700 /* Recursively merge in the base types' (if any) dicts. */
1701 bases = PyObject_GetAttrString(aclass, "__bases__");
1702 if (bases == NULL)
1703 PyErr_Clear();
1704 else {
1705 /* We have no guarantee that bases is a real tuple */
1706 int i, n;
1707 n = PySequence_Size(bases); /* This better be right */
1708 if (n < 0)
1709 PyErr_Clear();
1710 else {
1711 for (i = 0; i < n; i++) {
1712 int status;
1713 PyObject *base = PySequence_GetItem(bases, i);
1714 if (base == NULL) {
1715 Py_DECREF(bases);
1716 return -1;
1718 status = merge_class_dict(dict, base);
1719 Py_DECREF(base);
1720 if (status < 0) {
1721 Py_DECREF(bases);
1722 return -1;
1726 Py_DECREF(bases);
1728 return 0;
1731 /* Helper for PyObject_Dir.
1732 If obj has an attr named attrname that's a list, merge its string
1733 elements into keys of dict.
1734 Return 0 on success, -1 on error. Errors due to not finding the attr,
1735 or the attr not being a list, are suppressed.
1738 static int
1739 merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
1741 PyObject *list;
1742 int result = 0;
1744 assert(PyDict_Check(dict));
1745 assert(obj);
1746 assert(attrname);
1748 list = PyObject_GetAttrString(obj, attrname);
1749 if (list == NULL)
1750 PyErr_Clear();
1752 else if (PyList_Check(list)) {
1753 int i;
1754 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1755 PyObject *item = PyList_GET_ITEM(list, i);
1756 if (PyString_Check(item)) {
1757 result = PyDict_SetItem(dict, item, Py_None);
1758 if (result < 0)
1759 break;
1764 Py_XDECREF(list);
1765 return result;
1768 /* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1769 docstring, which should be kept in synch with this implementation. */
1771 PyObject *
1772 PyObject_Dir(PyObject *arg)
1774 /* Set exactly one of these non-NULL before the end. */
1775 PyObject *result = NULL; /* result list */
1776 PyObject *masterdict = NULL; /* result is masterdict.keys() */
1778 /* If NULL arg, return the locals. */
1779 if (arg == NULL) {
1780 PyObject *locals = PyEval_GetLocals();
1781 if (locals == NULL)
1782 goto error;
1783 result = PyDict_Keys(locals);
1784 if (result == NULL)
1785 goto error;
1788 /* Elif this is some form of module, we only want its dict. */
1789 else if (PyModule_Check(arg)) {
1790 masterdict = PyObject_GetAttrString(arg, "__dict__");
1791 if (masterdict == NULL)
1792 goto error;
1793 if (!PyDict_Check(masterdict)) {
1794 PyErr_SetString(PyExc_TypeError,
1795 "module.__dict__ is not a dictionary");
1796 goto error;
1800 /* Elif some form of type or class, grab its dict and its bases.
1801 We deliberately don't suck up its __class__, as methods belonging
1802 to the metaclass would probably be more confusing than helpful. */
1803 else if (PyType_Check(arg) || PyClass_Check(arg)) {
1804 masterdict = PyDict_New();
1805 if (masterdict == NULL)
1806 goto error;
1807 if (merge_class_dict(masterdict, arg) < 0)
1808 goto error;
1811 /* Else look at its dict, and the attrs reachable from its class. */
1812 else {
1813 PyObject *itsclass;
1814 /* Create a dict to start with. CAUTION: Not everything
1815 responding to __dict__ returns a dict! */
1816 masterdict = PyObject_GetAttrString(arg, "__dict__");
1817 if (masterdict == NULL) {
1818 PyErr_Clear();
1819 masterdict = PyDict_New();
1821 else if (!PyDict_Check(masterdict)) {
1822 Py_DECREF(masterdict);
1823 masterdict = PyDict_New();
1825 else {
1826 /* The object may have returned a reference to its
1827 dict, so copy it to avoid mutating it. */
1828 PyObject *temp = PyDict_Copy(masterdict);
1829 Py_DECREF(masterdict);
1830 masterdict = temp;
1832 if (masterdict == NULL)
1833 goto error;
1835 /* Merge in __members__ and __methods__ (if any).
1836 XXX Would like this to go away someday; for now, it's
1837 XXX needed to get at im_self etc of method objects. */
1838 if (merge_list_attr(masterdict, arg, "__members__") < 0)
1839 goto error;
1840 if (merge_list_attr(masterdict, arg, "__methods__") < 0)
1841 goto error;
1843 /* Merge in attrs reachable from its class.
1844 CAUTION: Not all objects have a __class__ attr. */
1845 itsclass = PyObject_GetAttrString(arg, "__class__");
1846 if (itsclass == NULL)
1847 PyErr_Clear();
1848 else {
1849 int status = merge_class_dict(masterdict, itsclass);
1850 Py_DECREF(itsclass);
1851 if (status < 0)
1852 goto error;
1856 assert((result == NULL) ^ (masterdict == NULL));
1857 if (masterdict != NULL) {
1858 /* The result comes from its keys. */
1859 assert(result == NULL);
1860 result = PyDict_Keys(masterdict);
1861 if (result == NULL)
1862 goto error;
1865 assert(result);
1866 if (PyList_Sort(result) != 0)
1867 goto error;
1868 else
1869 goto normal_return;
1871 error:
1872 Py_XDECREF(result);
1873 result = NULL;
1874 /* fall through */
1875 normal_return:
1876 Py_XDECREF(masterdict);
1877 return result;
1881 NoObject is usable as a non-NULL undefined value, used by the macro None.
1882 There is (and should be!) no way to create other objects of this type,
1883 so there is exactly one (which is indestructible, by the way).
1884 (XXX This type and the type of NotImplemented below should be unified.)
1887 /* ARGSUSED */
1888 static PyObject *
1889 none_repr(PyObject *op)
1891 return PyString_FromString("None");
1894 /* ARGUSED */
1895 static void
1896 none_dealloc(PyObject* ignore)
1898 /* This should never get called, but we also don't want to SEGV if
1899 * we accidently decref None out of existance.
1901 Py_FatalError("deallocating None");
1905 static PyTypeObject PyNone_Type = {
1906 PyObject_HEAD_INIT(&PyType_Type)
1908 "NoneType",
1911 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
1912 0, /*tp_print*/
1913 0, /*tp_getattr*/
1914 0, /*tp_setattr*/
1915 0, /*tp_compare*/
1916 (reprfunc)none_repr, /*tp_repr*/
1917 0, /*tp_as_number*/
1918 0, /*tp_as_sequence*/
1919 0, /*tp_as_mapping*/
1920 0, /*tp_hash */
1923 PyObject _Py_NoneStruct = {
1924 PyObject_HEAD_INIT(&PyNone_Type)
1927 /* NotImplemented is an object that can be used to signal that an
1928 operation is not implemented for the given type combination. */
1930 static PyObject *
1931 NotImplemented_repr(PyObject *op)
1933 return PyString_FromString("NotImplemented");
1936 static PyTypeObject PyNotImplemented_Type = {
1937 PyObject_HEAD_INIT(&PyType_Type)
1939 "NotImplementedType",
1942 (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/
1943 0, /*tp_print*/
1944 0, /*tp_getattr*/
1945 0, /*tp_setattr*/
1946 0, /*tp_compare*/
1947 (reprfunc)NotImplemented_repr, /*tp_repr*/
1948 0, /*tp_as_number*/
1949 0, /*tp_as_sequence*/
1950 0, /*tp_as_mapping*/
1951 0, /*tp_hash */
1954 PyObject _Py_NotImplementedStruct = {
1955 PyObject_HEAD_INIT(&PyNotImplemented_Type)
1958 void
1959 _Py_ReadyTypes(void)
1961 if (PyType_Ready(&PyType_Type) < 0)
1962 Py_FatalError("Can't initialize 'type'");
1964 if (PyType_Ready(&PyBool_Type) < 0)
1965 Py_FatalError("Can't initialize 'bool'");
1967 if (PyType_Ready(&PyString_Type) < 0)
1968 Py_FatalError("Can't initialize 'str'");
1970 if (PyType_Ready(&PyList_Type) < 0)
1971 Py_FatalError("Can't initialize 'list'");
1973 if (PyType_Ready(&PyNone_Type) < 0)
1974 Py_FatalError("Can't initialize type(None)");
1976 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1977 Py_FatalError("Can't initialize type(NotImplemented)");
1981 #ifdef Py_TRACE_REFS
1983 void
1984 _Py_NewReference(PyObject *op)
1986 _Py_INC_REFTOTAL;
1987 op->ob_refcnt = 1;
1988 _Py_AddToAllObjects(op, 1);
1989 _Py_INC_TPALLOCS(op);
1992 void
1993 _Py_ForgetReference(register PyObject *op)
1995 #ifdef SLOW_UNREF_CHECK
1996 register PyObject *p;
1997 #endif
1998 if (op->ob_refcnt < 0)
1999 Py_FatalError("UNREF negative refcnt");
2000 if (op == &refchain ||
2001 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
2002 Py_FatalError("UNREF invalid object");
2003 #ifdef SLOW_UNREF_CHECK
2004 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
2005 if (p == op)
2006 break;
2008 if (p == &refchain) /* Not found */
2009 Py_FatalError("UNREF unknown object");
2010 #endif
2011 op->_ob_next->_ob_prev = op->_ob_prev;
2012 op->_ob_prev->_ob_next = op->_ob_next;
2013 op->_ob_next = op->_ob_prev = NULL;
2014 _Py_INC_TPFREES(op);
2017 void
2018 _Py_Dealloc(PyObject *op)
2020 destructor dealloc = op->ob_type->tp_dealloc;
2021 _Py_ForgetReference(op);
2022 (*dealloc)(op);
2025 /* Print all live objects. Because PyObject_Print is called, the
2026 * interpreter must be in a healthy state.
2028 void
2029 _Py_PrintReferences(FILE *fp)
2031 PyObject *op;
2032 fprintf(fp, "Remaining objects:\n");
2033 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
2034 fprintf(fp, "%p [%d] ", op, op->ob_refcnt);
2035 if (PyObject_Print(op, fp, 0) != 0)
2036 PyErr_Clear();
2037 putc('\n', fp);
2041 /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
2042 * doesn't make any calls to the Python C API, so is always safe to call.
2044 void
2045 _Py_PrintReferenceAddresses(FILE *fp)
2047 PyObject *op;
2048 fprintf(fp, "Remaining object addresses:\n");
2049 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
2050 fprintf(fp, "%p [%d] %s\n", op, op->ob_refcnt,
2051 op->ob_type->tp_name);
2054 PyObject *
2055 _Py_GetObjects(PyObject *self, PyObject *args)
2057 int i, n;
2058 PyObject *t = NULL;
2059 PyObject *res, *op;
2061 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2062 return NULL;
2063 op = refchain._ob_next;
2064 res = PyList_New(0);
2065 if (res == NULL)
2066 return NULL;
2067 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2068 while (op == self || op == args || op == res || op == t ||
2069 (t != NULL && op->ob_type != (PyTypeObject *) t)) {
2070 op = op->_ob_next;
2071 if (op == &refchain)
2072 return res;
2074 if (PyList_Append(res, op) < 0) {
2075 Py_DECREF(res);
2076 return NULL;
2078 op = op->_ob_next;
2080 return res;
2083 #endif
2086 /* Hack to force loading of cobject.o */
2087 PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
2090 /* Hack to force loading of abstract.o */
2091 int (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
2094 /* Python's malloc wrappers (see pymem.h) */
2096 void *
2097 PyMem_Malloc(size_t nbytes)
2099 return PyMem_MALLOC(nbytes);
2102 void *
2103 PyMem_Realloc(void *p, size_t nbytes)
2105 return PyMem_REALLOC(p, nbytes);
2108 void
2109 PyMem_Free(void *p)
2111 PyMem_FREE(p);
2115 /* These methods are used to control infinite recursion in repr, str, print,
2116 etc. Container objects that may recursively contain themselves,
2117 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2118 Py_ReprLeave() to avoid infinite recursion.
2120 Py_ReprEnter() returns 0 the first time it is called for a particular
2121 object and 1 every time thereafter. It returns -1 if an exception
2122 occurred. Py_ReprLeave() has no return value.
2124 See dictobject.c and listobject.c for examples of use.
2127 #define KEY "Py_Repr"
2130 Py_ReprEnter(PyObject *obj)
2132 PyObject *dict;
2133 PyObject *list;
2134 int i;
2136 dict = PyThreadState_GetDict();
2137 if (dict == NULL)
2138 return 0;
2139 list = PyDict_GetItemString(dict, KEY);
2140 if (list == NULL) {
2141 list = PyList_New(0);
2142 if (list == NULL)
2143 return -1;
2144 if (PyDict_SetItemString(dict, KEY, list) < 0)
2145 return -1;
2146 Py_DECREF(list);
2148 i = PyList_GET_SIZE(list);
2149 while (--i >= 0) {
2150 if (PyList_GET_ITEM(list, i) == obj)
2151 return 1;
2153 PyList_Append(list, obj);
2154 return 0;
2157 void
2158 Py_ReprLeave(PyObject *obj)
2160 PyObject *dict;
2161 PyObject *list;
2162 int i;
2164 dict = PyThreadState_GetDict();
2165 if (dict == NULL)
2166 return;
2167 list = PyDict_GetItemString(dict, KEY);
2168 if (list == NULL || !PyList_Check(list))
2169 return;
2170 i = PyList_GET_SIZE(list);
2171 /* Count backwards because we always expect obj to be list[-1] */
2172 while (--i >= 0) {
2173 if (PyList_GET_ITEM(list, i) == obj) {
2174 PyList_SetSlice(list, i, i + 1, NULL);
2175 break;
2180 /* Trashcan support. */
2182 /* Current call-stack depth of tp_dealloc calls. */
2183 int _PyTrash_delete_nesting = 0;
2185 /* List of objects that still need to be cleaned up, singly linked via their
2186 * gc headers' gc_prev pointers.
2188 PyObject *_PyTrash_delete_later = NULL;
2190 /* Add op to the _PyTrash_delete_later list. Called when the current
2191 * call-stack depth gets large. op must be a currently untracked gc'ed
2192 * object, with refcount 0. Py_DECREF must already have been called on it.
2194 void
2195 _PyTrash_deposit_object(PyObject *op)
2197 assert(PyObject_IS_GC(op));
2198 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2199 assert(op->ob_refcnt == 0);
2200 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2201 _PyTrash_delete_later = op;
2204 /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2205 * the call-stack unwinds again.
2207 void
2208 _PyTrash_destroy_chain(void)
2210 while (_PyTrash_delete_later) {
2211 PyObject *op = _PyTrash_delete_later;
2212 destructor dealloc = op->ob_type->tp_dealloc;
2214 _PyTrash_delete_later =
2215 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2217 /* Call the deallocator directly. This used to try to
2218 * fool Py_DECREF into calling it indirectly, but
2219 * Py_DECREF was already called on this object, and in
2220 * assorted non-release builds calling Py_DECREF again ends
2221 * up distorting allocation statistics.
2223 assert(op->ob_refcnt == 0);
2224 ++_PyTrash_delete_nesting;
2225 (*dealloc)(op);
2226 --_PyTrash_delete_nesting;