Issue #2143: Fix embedded readline() hang on SSL socket EOF.
[python.git] / Objects / object.c
bloba10ac7ce19f3e0e67e4d59d0f0b119261be026c0
2 /* Generic object operations; and implementation of None (NoObject) */
4 #include "Python.h"
6 #ifdef __cplusplus
7 extern "C" {
8 #endif
10 #ifdef Py_REF_DEBUG
11 Py_ssize_t _Py_RefTotal;
13 Py_ssize_t
14 _Py_GetRefTotal(void)
16 PyObject *o;
17 Py_ssize_t total = _Py_RefTotal;
18 /* ignore the references to the dummy object of the dicts and sets
19 because they are not reliable and not useful (now that the
20 hash table code is well-tested) */
21 o = _PyDict_Dummy();
22 if (o != NULL)
23 total -= o->ob_refcnt;
24 o = _PySet_Dummy();
25 if (o != NULL)
26 total -= o->ob_refcnt;
27 return total;
29 #endif /* Py_REF_DEBUG */
31 int Py_DivisionWarningFlag;
32 int Py_Py3kWarningFlag;
34 /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
35 These are used by the individual routines for object creation.
36 Do not call them otherwise, they do not initialize the object! */
38 #ifdef Py_TRACE_REFS
39 /* Head of circular doubly-linked list of all objects. These are linked
40 * together via the _ob_prev and _ob_next members of a PyObject, which
41 * exist only in a Py_TRACE_REFS build.
43 static PyObject refchain = {&refchain, &refchain};
45 /* Insert op at the front of the list of all objects. If force is true,
46 * op is added even if _ob_prev and _ob_next are non-NULL already. If
47 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
48 * force should be true if and only if op points to freshly allocated,
49 * uninitialized memory, or you've unlinked op from the list and are
50 * relinking it into the front.
51 * Note that objects are normally added to the list via _Py_NewReference,
52 * which is called by PyObject_Init. Not all objects are initialized that
53 * way, though; exceptions include statically allocated type objects, and
54 * statically allocated singletons (like Py_True and Py_None).
56 void
57 _Py_AddToAllObjects(PyObject *op, int force)
59 #ifdef Py_DEBUG
60 if (!force) {
61 /* If it's initialized memory, op must be in or out of
62 * the list unambiguously.
64 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
66 #endif
67 if (force || op->_ob_prev == NULL) {
68 op->_ob_next = refchain._ob_next;
69 op->_ob_prev = &refchain;
70 refchain._ob_next->_ob_prev = op;
71 refchain._ob_next = op;
74 #endif /* Py_TRACE_REFS */
76 #ifdef COUNT_ALLOCS
77 static PyTypeObject *type_list;
78 /* All types are added to type_list, at least when
79 they get one object created. That makes them
80 immortal, which unfortunately contributes to
81 garbage itself. If unlist_types_without_objects
82 is set, they will be removed from the type_list
83 once the last object is deallocated. */
84 int unlist_types_without_objects;
85 extern int tuple_zero_allocs, fast_tuple_allocs;
86 extern int quick_int_allocs, quick_neg_int_allocs;
87 extern int null_strings, one_strings;
88 void
89 dump_counts(FILE* f)
91 PyTypeObject *tp;
93 for (tp = type_list; tp; tp = tp->tp_next)
94 fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",
95 tp->tp_name, tp->tp_allocs, tp->tp_frees,
96 tp->tp_maxalloc);
97 fprintf(f, "fast tuple allocs: %d, empty: %d\n",
98 fast_tuple_allocs, tuple_zero_allocs);
99 fprintf(f, "fast int allocs: pos: %d, neg: %d\n",
100 quick_int_allocs, quick_neg_int_allocs);
101 fprintf(f, "null strings: %d, 1-strings: %d\n",
102 null_strings, one_strings);
105 PyObject *
106 get_counts(void)
108 PyTypeObject *tp;
109 PyObject *result;
110 PyObject *v;
112 result = PyList_New(0);
113 if (result == NULL)
114 return NULL;
115 for (tp = type_list; tp; tp = tp->tp_next) {
116 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
117 tp->tp_frees, tp->tp_maxalloc);
118 if (v == NULL) {
119 Py_DECREF(result);
120 return NULL;
122 if (PyList_Append(result, v) < 0) {
123 Py_DECREF(v);
124 Py_DECREF(result);
125 return NULL;
127 Py_DECREF(v);
129 return result;
132 void
133 inc_count(PyTypeObject *tp)
135 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
136 /* first time; insert in linked list */
137 if (tp->tp_next != NULL) /* sanity check */
138 Py_FatalError("XXX inc_count sanity check");
139 if (type_list)
140 type_list->tp_prev = tp;
141 tp->tp_next = type_list;
142 /* Note that as of Python 2.2, heap-allocated type objects
143 * can go away, but this code requires that they stay alive
144 * until program exit. That's why we're careful with
145 * refcounts here. type_list gets a new reference to tp,
146 * while ownership of the reference type_list used to hold
147 * (if any) was transferred to tp->tp_next in the line above.
148 * tp is thus effectively immortal after this.
150 Py_INCREF(tp);
151 type_list = tp;
152 #ifdef Py_TRACE_REFS
153 /* Also insert in the doubly-linked list of all objects,
154 * if not already there.
156 _Py_AddToAllObjects((PyObject *)tp, 0);
157 #endif
159 tp->tp_allocs++;
160 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
161 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
164 void dec_count(PyTypeObject *tp)
166 tp->tp_frees++;
167 if (unlist_types_without_objects &&
168 tp->tp_allocs == tp->tp_frees) {
169 /* unlink the type from type_list */
170 if (tp->tp_prev)
171 tp->tp_prev->tp_next = tp->tp_next;
172 else
173 type_list = tp->tp_next;
174 if (tp->tp_next)
175 tp->tp_next->tp_prev = tp->tp_prev;
176 tp->tp_next = tp->tp_prev = NULL;
177 Py_DECREF(tp);
181 #endif
183 #ifdef Py_REF_DEBUG
184 /* Log a fatal error; doesn't return. */
185 void
186 _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
188 char buf[300];
190 PyOS_snprintf(buf, sizeof(buf),
191 "%s:%i object at %p has negative ref count "
192 "%" PY_FORMAT_SIZE_T "d",
193 fname, lineno, op, op->ob_refcnt);
194 Py_FatalError(buf);
197 #endif /* Py_REF_DEBUG */
199 void
200 Py_IncRef(PyObject *o)
202 Py_XINCREF(o);
205 void
206 Py_DecRef(PyObject *o)
208 Py_XDECREF(o);
211 PyObject *
212 PyObject_Init(PyObject *op, PyTypeObject *tp)
214 if (op == NULL)
215 return PyErr_NoMemory();
216 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
217 Py_TYPE(op) = tp;
218 _Py_NewReference(op);
219 return op;
222 PyVarObject *
223 PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
225 if (op == NULL)
226 return (PyVarObject *) PyErr_NoMemory();
227 /* Any changes should be reflected in PyObject_INIT_VAR */
228 op->ob_size = size;
229 Py_TYPE(op) = tp;
230 _Py_NewReference((PyObject *)op);
231 return op;
234 PyObject *
235 _PyObject_New(PyTypeObject *tp)
237 PyObject *op;
238 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
239 if (op == NULL)
240 return PyErr_NoMemory();
241 return PyObject_INIT(op, tp);
244 PyVarObject *
245 _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
247 PyVarObject *op;
248 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
249 op = (PyVarObject *) PyObject_MALLOC(size);
250 if (op == NULL)
251 return (PyVarObject *)PyErr_NoMemory();
252 return PyObject_INIT_VAR(op, tp, nitems);
255 /* for binary compatibility with 2.2 */
256 #undef _PyObject_Del
257 void
258 _PyObject_Del(PyObject *op)
260 PyObject_FREE(op);
263 /* Implementation of PyObject_Print with recursion checking */
264 static int
265 internal_print(PyObject *op, FILE *fp, int flags, int nesting)
267 int ret = 0;
268 if (nesting > 10) {
269 PyErr_SetString(PyExc_RuntimeError, "print recursion");
270 return -1;
272 if (PyErr_CheckSignals())
273 return -1;
274 #ifdef USE_STACKCHECK
275 if (PyOS_CheckStack()) {
276 PyErr_SetString(PyExc_MemoryError, "stack overflow");
277 return -1;
279 #endif
280 clearerr(fp); /* Clear any previous error condition */
281 if (op == NULL) {
282 Py_BEGIN_ALLOW_THREADS
283 fprintf(fp, "<nil>");
284 Py_END_ALLOW_THREADS
286 else {
287 if (op->ob_refcnt <= 0)
288 /* XXX(twouters) cast refcount to long until %zd is
289 universally available */
290 Py_BEGIN_ALLOW_THREADS
291 fprintf(fp, "<refcnt %ld at %p>",
292 (long)op->ob_refcnt, op);
293 Py_END_ALLOW_THREADS
294 else if (Py_TYPE(op)->tp_print == NULL) {
295 PyObject *s;
296 if (flags & Py_PRINT_RAW)
297 s = PyObject_Str(op);
298 else
299 s = PyObject_Repr(op);
300 if (s == NULL)
301 ret = -1;
302 else {
303 ret = internal_print(s, fp, Py_PRINT_RAW,
304 nesting+1);
306 Py_XDECREF(s);
308 else
309 ret = (*Py_TYPE(op)->tp_print)(op, fp, flags);
311 if (ret == 0) {
312 if (ferror(fp)) {
313 PyErr_SetFromErrno(PyExc_IOError);
314 clearerr(fp);
315 ret = -1;
318 return ret;
322 PyObject_Print(PyObject *op, FILE *fp, int flags)
324 return internal_print(op, fp, flags, 0);
328 /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
329 void _PyObject_Dump(PyObject* op)
331 if (op == NULL)
332 fprintf(stderr, "NULL\n");
333 else {
334 fprintf(stderr, "object : ");
335 (void)PyObject_Print(op, stderr, 0);
336 /* XXX(twouters) cast refcount to long until %zd is
337 universally available */
338 fprintf(stderr, "\n"
339 "type : %s\n"
340 "refcount: %ld\n"
341 "address : %p\n",
342 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
343 (long)op->ob_refcnt,
344 op);
348 PyObject *
349 PyObject_Repr(PyObject *v)
351 if (PyErr_CheckSignals())
352 return NULL;
353 #ifdef USE_STACKCHECK
354 if (PyOS_CheckStack()) {
355 PyErr_SetString(PyExc_MemoryError, "stack overflow");
356 return NULL;
358 #endif
359 if (v == NULL)
360 return PyString_FromString("<NULL>");
361 else if (Py_TYPE(v)->tp_repr == NULL)
362 return PyString_FromFormat("<%s object at %p>",
363 Py_TYPE(v)->tp_name, v);
364 else {
365 PyObject *res;
366 res = (*Py_TYPE(v)->tp_repr)(v);
367 if (res == NULL)
368 return NULL;
369 #ifdef Py_USING_UNICODE
370 if (PyUnicode_Check(res)) {
371 PyObject* str;
372 str = PyUnicode_AsEncodedString(res, NULL, NULL);
373 Py_DECREF(res);
374 if (str)
375 res = str;
376 else
377 return NULL;
379 #endif
380 if (!PyString_Check(res)) {
381 PyErr_Format(PyExc_TypeError,
382 "__repr__ returned non-string (type %.200s)",
383 Py_TYPE(res)->tp_name);
384 Py_DECREF(res);
385 return NULL;
387 return res;
391 PyObject *
392 _PyObject_Str(PyObject *v)
394 PyObject *res;
395 int type_ok;
396 if (v == NULL)
397 return PyString_FromString("<NULL>");
398 if (PyString_CheckExact(v)) {
399 Py_INCREF(v);
400 return v;
402 #ifdef Py_USING_UNICODE
403 if (PyUnicode_CheckExact(v)) {
404 Py_INCREF(v);
405 return v;
407 #endif
408 if (Py_TYPE(v)->tp_str == NULL)
409 return PyObject_Repr(v);
411 /* It is possible for a type to have a tp_str representation that loops
412 infinitely. */
413 if (Py_EnterRecursiveCall(" while getting the str of an object"))
414 return NULL;
415 res = (*Py_TYPE(v)->tp_str)(v);
416 Py_LeaveRecursiveCall();
417 if (res == NULL)
418 return NULL;
419 type_ok = PyString_Check(res);
420 #ifdef Py_USING_UNICODE
421 type_ok = type_ok || PyUnicode_Check(res);
422 #endif
423 if (!type_ok) {
424 PyErr_Format(PyExc_TypeError,
425 "__str__ returned non-string (type %.200s)",
426 Py_TYPE(res)->tp_name);
427 Py_DECREF(res);
428 return NULL;
430 return res;
433 PyObject *
434 PyObject_Str(PyObject *v)
436 PyObject *res = _PyObject_Str(v);
437 if (res == NULL)
438 return NULL;
439 #ifdef Py_USING_UNICODE
440 if (PyUnicode_Check(res)) {
441 PyObject* str;
442 str = PyUnicode_AsEncodedString(res, NULL, NULL);
443 Py_DECREF(res);
444 if (str)
445 res = str;
446 else
447 return NULL;
449 #endif
450 assert(PyString_Check(res));
451 return res;
454 #ifdef Py_USING_UNICODE
455 PyObject *
456 PyObject_Unicode(PyObject *v)
458 PyObject *res;
459 PyObject *func;
460 PyObject *str;
461 static PyObject *unicodestr;
463 if (v == NULL) {
464 res = PyString_FromString("<NULL>");
465 if (res == NULL)
466 return NULL;
467 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
468 Py_DECREF(res);
469 return str;
470 } else if (PyUnicode_CheckExact(v)) {
471 Py_INCREF(v);
472 return v;
474 /* XXX As soon as we have a tp_unicode slot, we should
475 check this before trying the __unicode__
476 method. */
477 if (unicodestr == NULL) {
478 unicodestr= PyString_InternFromString("__unicode__");
479 if (unicodestr == NULL)
480 return NULL;
482 func = PyObject_GetAttr(v, unicodestr);
483 if (func != NULL) {
484 res = PyEval_CallObject(func, (PyObject *)NULL);
485 Py_DECREF(func);
487 else {
488 PyErr_Clear();
489 if (PyUnicode_Check(v)) {
490 /* For a Unicode subtype that's didn't overwrite __unicode__,
491 return a true Unicode object with the same data. */
492 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
493 PyUnicode_GET_SIZE(v));
495 if (PyString_CheckExact(v)) {
496 Py_INCREF(v);
497 res = v;
499 else {
500 if (Py_TYPE(v)->tp_str != NULL)
501 res = (*Py_TYPE(v)->tp_str)(v);
502 else
503 res = PyObject_Repr(v);
506 if (res == NULL)
507 return NULL;
508 if (!PyUnicode_Check(res)) {
509 str = PyUnicode_FromEncodedObject(res, NULL, "strict");
510 Py_DECREF(res);
511 res = str;
513 return res;
515 #endif
518 /* Helper to warn about deprecated tp_compare return values. Return:
519 -2 for an exception;
520 -1 if v < w;
521 0 if v == w;
522 1 if v > w.
523 (This function cannot return 2.)
525 static int
526 adjust_tp_compare(int c)
528 if (PyErr_Occurred()) {
529 if (c != -1 && c != -2) {
530 PyObject *t, *v, *tb;
531 PyErr_Fetch(&t, &v, &tb);
532 if (PyErr_Warn(PyExc_RuntimeWarning,
533 "tp_compare didn't return -1 or -2 "
534 "for exception") < 0) {
535 Py_XDECREF(t);
536 Py_XDECREF(v);
537 Py_XDECREF(tb);
539 else
540 PyErr_Restore(t, v, tb);
542 return -2;
544 else if (c < -1 || c > 1) {
545 if (PyErr_Warn(PyExc_RuntimeWarning,
546 "tp_compare didn't return -1, 0 or 1") < 0)
547 return -2;
548 else
549 return c < -1 ? -1 : 1;
551 else {
552 assert(c >= -1 && c <= 1);
553 return c;
558 /* Macro to get the tp_richcompare field of a type if defined */
559 #define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
560 ? (t)->tp_richcompare : NULL)
562 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
563 int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
565 /* Try a genuine rich comparison, returning an object. Return:
566 NULL for exception;
567 NotImplemented if this particular rich comparison is not implemented or
568 undefined;
569 some object not equal to NotImplemented if it is implemented
570 (this latter object may not be a Boolean).
572 static PyObject *
573 try_rich_compare(PyObject *v, PyObject *w, int op)
575 richcmpfunc f;
576 PyObject *res;
578 if (v->ob_type != w->ob_type &&
579 PyType_IsSubtype(w->ob_type, v->ob_type) &&
580 (f = RICHCOMPARE(w->ob_type)) != NULL) {
581 res = (*f)(w, v, _Py_SwappedOp[op]);
582 if (res != Py_NotImplemented)
583 return res;
584 Py_DECREF(res);
586 if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
587 res = (*f)(v, w, op);
588 if (res != Py_NotImplemented)
589 return res;
590 Py_DECREF(res);
592 if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
593 return (*f)(w, v, _Py_SwappedOp[op]);
595 res = Py_NotImplemented;
596 Py_INCREF(res);
597 return res;
600 /* Try a genuine rich comparison, returning an int. Return:
601 -1 for exception (including the case where try_rich_compare() returns an
602 object that's not a Boolean);
603 0 if the outcome is false;
604 1 if the outcome is true;
605 2 if this particular rich comparison is not implemented or undefined.
607 static int
608 try_rich_compare_bool(PyObject *v, PyObject *w, int op)
610 PyObject *res;
611 int ok;
613 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
614 return 2; /* Shortcut, avoid INCREF+DECREF */
615 res = try_rich_compare(v, w, op);
616 if (res == NULL)
617 return -1;
618 if (res == Py_NotImplemented) {
619 Py_DECREF(res);
620 return 2;
622 ok = PyObject_IsTrue(res);
623 Py_DECREF(res);
624 return ok;
627 /* Try rich comparisons to determine a 3-way comparison. Return:
628 -2 for an exception;
629 -1 if v < w;
630 0 if v == w;
631 1 if v > w;
632 2 if this particular rich comparison is not implemented or undefined.
634 static int
635 try_rich_to_3way_compare(PyObject *v, PyObject *w)
637 static struct { int op; int outcome; } tries[3] = {
638 /* Try this operator, and if it is true, use this outcome: */
639 {Py_EQ, 0},
640 {Py_LT, -1},
641 {Py_GT, 1},
643 int i;
645 if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
646 return 2; /* Shortcut */
648 for (i = 0; i < 3; i++) {
649 switch (try_rich_compare_bool(v, w, tries[i].op)) {
650 case -1:
651 return -2;
652 case 1:
653 return tries[i].outcome;
657 return 2;
660 /* Try a 3-way comparison, returning an int. Return:
661 -2 for an exception;
662 -1 if v < w;
663 0 if v == w;
664 1 if v > w;
665 2 if this particular 3-way comparison is not implemented or undefined.
667 static int
668 try_3way_compare(PyObject *v, PyObject *w)
670 int c;
671 cmpfunc f;
673 /* Comparisons involving instances are given to instance_compare,
674 which has the same return conventions as this function. */
676 f = v->ob_type->tp_compare;
677 if (PyInstance_Check(v))
678 return (*f)(v, w);
679 if (PyInstance_Check(w))
680 return (*w->ob_type->tp_compare)(v, w);
682 /* If both have the same (non-NULL) tp_compare, use it. */
683 if (f != NULL && f == w->ob_type->tp_compare) {
684 c = (*f)(v, w);
685 return adjust_tp_compare(c);
688 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
689 if (f == _PyObject_SlotCompare ||
690 w->ob_type->tp_compare == _PyObject_SlotCompare)
691 return _PyObject_SlotCompare(v, w);
693 /* If we're here, v and w,
694 a) are not instances;
695 b) have different types or a type without tp_compare; and
696 c) don't have a user-defined tp_compare.
697 tp_compare implementations in C assume that both arguments
698 have their type, so we give up if the coercion fails or if
699 it yields types which are still incompatible (which can
700 happen with a user-defined nb_coerce).
702 c = PyNumber_CoerceEx(&v, &w);
703 if (c < 0)
704 return -2;
705 if (c > 0)
706 return 2;
707 f = v->ob_type->tp_compare;
708 if (f != NULL && f == w->ob_type->tp_compare) {
709 c = (*f)(v, w);
710 Py_DECREF(v);
711 Py_DECREF(w);
712 return adjust_tp_compare(c);
715 /* No comparison defined */
716 Py_DECREF(v);
717 Py_DECREF(w);
718 return 2;
721 /* Final fallback 3-way comparison, returning an int. Return:
722 -2 if an error occurred;
723 -1 if v < w;
724 0 if v == w;
725 1 if v > w.
727 static int
728 default_3way_compare(PyObject *v, PyObject *w)
730 int c;
731 const char *vname, *wname;
733 if (v->ob_type == w->ob_type) {
734 /* When comparing these pointers, they must be cast to
735 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
736 * uintptr_t). ANSI specifies that pointer compares other
737 * than == and != to non-related structures are undefined.
739 Py_uintptr_t vv = (Py_uintptr_t)v;
740 Py_uintptr_t ww = (Py_uintptr_t)w;
741 return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
744 /* None is smaller than anything */
745 if (v == Py_None)
746 return -1;
747 if (w == Py_None)
748 return 1;
750 /* different type: compare type names; numbers are smaller */
751 if (PyNumber_Check(v))
752 vname = "";
753 else
754 vname = v->ob_type->tp_name;
755 if (PyNumber_Check(w))
756 wname = "";
757 else
758 wname = w->ob_type->tp_name;
759 c = strcmp(vname, wname);
760 if (c < 0)
761 return -1;
762 if (c > 0)
763 return 1;
764 /* Same type name, or (more likely) incomparable numeric types */
765 return ((Py_uintptr_t)(v->ob_type) < (
766 Py_uintptr_t)(w->ob_type)) ? -1 : 1;
769 /* Do a 3-way comparison, by hook or by crook. Return:
770 -2 for an exception (but see below);
771 -1 if v < w;
772 0 if v == w;
773 1 if v > w;
774 BUT: if the object implements a tp_compare function, it returns
775 whatever this function returns (whether with an exception or not).
777 static int
778 do_cmp(PyObject *v, PyObject *w)
780 int c;
781 cmpfunc f;
783 if (v->ob_type == w->ob_type
784 && (f = v->ob_type->tp_compare) != NULL) {
785 c = (*f)(v, w);
786 if (PyInstance_Check(v)) {
787 /* Instance tp_compare has a different signature.
788 But if it returns undefined we fall through. */
789 if (c != 2)
790 return c;
791 /* Else fall through to try_rich_to_3way_compare() */
793 else
794 return adjust_tp_compare(c);
796 /* We only get here if one of the following is true:
797 a) v and w have different types
798 b) v and w have the same type, which doesn't have tp_compare
799 c) v and w are instances, and either __cmp__ is not defined or
800 __cmp__ returns NotImplemented
802 c = try_rich_to_3way_compare(v, w);
803 if (c < 2)
804 return c;
805 c = try_3way_compare(v, w);
806 if (c < 2)
807 return c;
808 return default_3way_compare(v, w);
811 /* Compare v to w. Return
812 -1 if v < w or exception (PyErr_Occurred() true in latter case).
813 0 if v == w.
814 1 if v > w.
815 XXX The docs (C API manual) say the return value is undefined in case
816 XXX of error.
819 PyObject_Compare(PyObject *v, PyObject *w)
821 int result;
823 if (v == NULL || w == NULL) {
824 PyErr_BadInternalCall();
825 return -1;
827 if (v == w)
828 return 0;
829 if (Py_EnterRecursiveCall(" in cmp"))
830 return -1;
831 result = do_cmp(v, w);
832 Py_LeaveRecursiveCall();
833 return result < 0 ? -1 : result;
836 /* Return (new reference to) Py_True or Py_False. */
837 static PyObject *
838 convert_3way_to_object(int op, int c)
840 PyObject *result;
841 switch (op) {
842 case Py_LT: c = c < 0; break;
843 case Py_LE: c = c <= 0; break;
844 case Py_EQ: c = c == 0; break;
845 case Py_NE: c = c != 0; break;
846 case Py_GT: c = c > 0; break;
847 case Py_GE: c = c >= 0; break;
849 result = c ? Py_True : Py_False;
850 Py_INCREF(result);
851 return result;
854 /* We want a rich comparison but don't have one. Try a 3-way cmp instead.
855 Return
856 NULL if error
857 Py_True if v op w
858 Py_False if not (v op w)
860 static PyObject *
861 try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
863 int c;
865 c = try_3way_compare(v, w);
866 if (c >= 2) {
868 /* Py3K warning if types are not equal and comparison isn't == or != */
869 if (Py_Py3kWarningFlag &&
870 v->ob_type != w->ob_type && op != Py_EQ && op != Py_NE &&
871 PyErr_Warn(PyExc_DeprecationWarning,
872 "comparing unequal types not supported in 3.x.") < 0) {
873 return NULL;
876 c = default_3way_compare(v, w);
878 if (c <= -2)
879 return NULL;
880 return convert_3way_to_object(op, c);
883 /* Do rich comparison on v and w. Return
884 NULL if error
885 Else a new reference to an object other than Py_NotImplemented, usually(?):
886 Py_True if v op w
887 Py_False if not (v op w)
889 static PyObject *
890 do_richcmp(PyObject *v, PyObject *w, int op)
892 PyObject *res;
894 res = try_rich_compare(v, w, op);
895 if (res != Py_NotImplemented)
896 return res;
897 Py_DECREF(res);
899 return try_3way_to_rich_compare(v, w, op);
902 /* Return:
903 NULL for exception;
904 some object not equal to NotImplemented if it is implemented
905 (this latter object may not be a Boolean).
907 PyObject *
908 PyObject_RichCompare(PyObject *v, PyObject *w, int op)
910 PyObject *res;
912 assert(Py_LT <= op && op <= Py_GE);
913 if (Py_EnterRecursiveCall(" in cmp"))
914 return NULL;
916 /* If the types are equal, and not old-style instances, try to
917 get out cheap (don't bother with coercions etc.). */
918 if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
919 cmpfunc fcmp;
920 richcmpfunc frich = RICHCOMPARE(v->ob_type);
921 /* If the type has richcmp, try it first. try_rich_compare
922 tries it two-sided, which is not needed since we've a
923 single type only. */
924 if (frich != NULL) {
925 res = (*frich)(v, w, op);
926 if (res != Py_NotImplemented)
927 goto Done;
928 Py_DECREF(res);
930 /* No richcmp, or this particular richmp not implemented.
931 Try 3-way cmp. */
932 fcmp = v->ob_type->tp_compare;
933 if (fcmp != NULL) {
934 int c = (*fcmp)(v, w);
935 c = adjust_tp_compare(c);
936 if (c == -2) {
937 res = NULL;
938 goto Done;
940 res = convert_3way_to_object(op, c);
941 goto Done;
945 /* Fast path not taken, or couldn't deliver a useful result. */
946 res = do_richcmp(v, w, op);
947 Done:
948 Py_LeaveRecursiveCall();
949 return res;
952 /* Return -1 if error; 1 if v op w; 0 if not (v op w). */
954 PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
956 PyObject *res;
957 int ok;
959 /* Quick result when objects are the same.
960 Guarantees that identity implies equality. */
961 if (v == w) {
962 if (op == Py_EQ)
963 return 1;
964 else if (op == Py_NE)
965 return 0;
968 res = PyObject_RichCompare(v, w, op);
969 if (res == NULL)
970 return -1;
971 if (PyBool_Check(res))
972 ok = (res == Py_True);
973 else
974 ok = PyObject_IsTrue(res);
975 Py_DECREF(res);
976 return ok;
979 /* Set of hash utility functions to help maintaining the invariant that
980 if a==b then hash(a)==hash(b)
982 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
985 long
986 _Py_HashDouble(double v)
988 double intpart, fractpart;
989 int expo;
990 long hipart;
991 long x; /* the final hash value */
992 /* This is designed so that Python numbers of different types
993 * that compare equal hash to the same value; otherwise comparisons
994 * of mapping keys will turn out weird.
997 fractpart = modf(v, &intpart);
998 if (fractpart == 0.0) {
999 /* This must return the same hash as an equal int or long. */
1000 if (intpart > LONG_MAX || -intpart > LONG_MAX) {
1001 /* Convert to long and use its hash. */
1002 PyObject *plong; /* converted to Python long */
1003 if (Py_IS_INFINITY(intpart))
1004 /* can't convert to long int -- arbitrary */
1005 v = v < 0 ? -271828.0 : 314159.0;
1006 plong = PyLong_FromDouble(v);
1007 if (plong == NULL)
1008 return -1;
1009 x = PyObject_Hash(plong);
1010 Py_DECREF(plong);
1011 return x;
1013 /* Fits in a C long == a Python int, so is its own hash. */
1014 x = (long)intpart;
1015 if (x == -1)
1016 x = -2;
1017 return x;
1019 /* The fractional part is non-zero, so we don't have to worry about
1020 * making this match the hash of some other type.
1021 * Use frexp to get at the bits in the double.
1022 * Since the VAX D double format has 56 mantissa bits, which is the
1023 * most of any double format in use, each of these parts may have as
1024 * many as (but no more than) 56 significant bits.
1025 * So, assuming sizeof(long) >= 4, each part can be broken into two
1026 * longs; frexp and multiplication are used to do that.
1027 * Also, since the Cray double format has 15 exponent bits, which is
1028 * the most of any double format in use, shifting the exponent field
1029 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
1031 v = frexp(v, &expo);
1032 v *= 2147483648.0; /* 2**31 */
1033 hipart = (long)v; /* take the top 32 bits */
1034 v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1035 x = hipart + (long)v + (expo << 15);
1036 if (x == -1)
1037 x = -2;
1038 return x;
1041 long
1042 _Py_HashPointer(void *p)
1044 #if SIZEOF_LONG >= SIZEOF_VOID_P
1045 return (long)p;
1046 #else
1047 /* convert to a Python long and hash that */
1048 PyObject* longobj;
1049 long x;
1051 if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
1052 x = -1;
1053 goto finally;
1055 x = PyObject_Hash(longobj);
1057 finally:
1058 Py_XDECREF(longobj);
1059 return x;
1060 #endif
1064 long
1065 PyObject_Hash(PyObject *v)
1067 PyTypeObject *tp = v->ob_type;
1068 if (tp->tp_hash != NULL)
1069 return (*tp->tp_hash)(v);
1070 if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
1071 return _Py_HashPointer(v); /* Use address as hash value */
1073 /* If there's a cmp but no hash defined, the object can't be hashed */
1074 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1075 v->ob_type->tp_name);
1076 return -1;
1079 PyObject *
1080 PyObject_GetAttrString(PyObject *v, const char *name)
1082 PyObject *w, *res;
1084 if (Py_TYPE(v)->tp_getattr != NULL)
1085 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1086 w = PyString_InternFromString(name);
1087 if (w == NULL)
1088 return NULL;
1089 res = PyObject_GetAttr(v, w);
1090 Py_XDECREF(w);
1091 return res;
1095 PyObject_HasAttrString(PyObject *v, const char *name)
1097 PyObject *res = PyObject_GetAttrString(v, name);
1098 if (res != NULL) {
1099 Py_DECREF(res);
1100 return 1;
1102 PyErr_Clear();
1103 return 0;
1107 PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
1109 PyObject *s;
1110 int res;
1112 if (Py_TYPE(v)->tp_setattr != NULL)
1113 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1114 s = PyString_InternFromString(name);
1115 if (s == NULL)
1116 return -1;
1117 res = PyObject_SetAttr(v, s, w);
1118 Py_XDECREF(s);
1119 return res;
1122 PyObject *
1123 PyObject_GetAttr(PyObject *v, PyObject *name)
1125 PyTypeObject *tp = Py_TYPE(v);
1127 if (!PyString_Check(name)) {
1128 #ifdef Py_USING_UNICODE
1129 /* The Unicode to string conversion is done here because the
1130 existing tp_getattro slots expect a string object as name
1131 and we wouldn't want to break those. */
1132 if (PyUnicode_Check(name)) {
1133 name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1134 if (name == NULL)
1135 return NULL;
1137 else
1138 #endif
1140 PyErr_Format(PyExc_TypeError,
1141 "attribute name must be string, not '%.200s'",
1142 Py_TYPE(name)->tp_name);
1143 return NULL;
1146 if (tp->tp_getattro != NULL)
1147 return (*tp->tp_getattro)(v, name);
1148 if (tp->tp_getattr != NULL)
1149 return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1150 PyErr_Format(PyExc_AttributeError,
1151 "'%.50s' object has no attribute '%.400s'",
1152 tp->tp_name, PyString_AS_STRING(name));
1153 return NULL;
1157 PyObject_HasAttr(PyObject *v, PyObject *name)
1159 PyObject *res = PyObject_GetAttr(v, name);
1160 if (res != NULL) {
1161 Py_DECREF(res);
1162 return 1;
1164 PyErr_Clear();
1165 return 0;
1169 PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
1171 PyTypeObject *tp = Py_TYPE(v);
1172 int err;
1174 if (!PyString_Check(name)){
1175 #ifdef Py_USING_UNICODE
1176 /* The Unicode to string conversion is done here because the
1177 existing tp_setattro slots expect a string object as name
1178 and we wouldn't want to break those. */
1179 if (PyUnicode_Check(name)) {
1180 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1181 if (name == NULL)
1182 return -1;
1184 else
1185 #endif
1187 PyErr_Format(PyExc_TypeError,
1188 "attribute name must be string, not '%.200s'",
1189 Py_TYPE(name)->tp_name);
1190 return -1;
1193 else
1194 Py_INCREF(name);
1196 PyString_InternInPlace(&name);
1197 if (tp->tp_setattro != NULL) {
1198 err = (*tp->tp_setattro)(v, name, value);
1199 Py_DECREF(name);
1200 return err;
1202 if (tp->tp_setattr != NULL) {
1203 err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1204 Py_DECREF(name);
1205 return err;
1207 Py_DECREF(name);
1208 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1209 PyErr_Format(PyExc_TypeError,
1210 "'%.100s' object has no attributes "
1211 "(%s .%.100s)",
1212 tp->tp_name,
1213 value==NULL ? "del" : "assign to",
1214 PyString_AS_STRING(name));
1215 else
1216 PyErr_Format(PyExc_TypeError,
1217 "'%.100s' object has only read-only attributes "
1218 "(%s .%.100s)",
1219 tp->tp_name,
1220 value==NULL ? "del" : "assign to",
1221 PyString_AS_STRING(name));
1222 return -1;
1225 /* Helper to get a pointer to an object's __dict__ slot, if any */
1227 PyObject **
1228 _PyObject_GetDictPtr(PyObject *obj)
1230 Py_ssize_t dictoffset;
1231 PyTypeObject *tp = Py_TYPE(obj);
1233 if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1234 return NULL;
1235 dictoffset = tp->tp_dictoffset;
1236 if (dictoffset == 0)
1237 return NULL;
1238 if (dictoffset < 0) {
1239 Py_ssize_t tsize;
1240 size_t size;
1242 tsize = ((PyVarObject *)obj)->ob_size;
1243 if (tsize < 0)
1244 tsize = -tsize;
1245 size = _PyObject_VAR_SIZE(tp, tsize);
1247 dictoffset += (long)size;
1248 assert(dictoffset > 0);
1249 assert(dictoffset % SIZEOF_VOID_P == 0);
1251 return (PyObject **) ((char *)obj + dictoffset);
1254 PyObject *
1255 PyObject_SelfIter(PyObject *obj)
1257 Py_INCREF(obj);
1258 return obj;
1261 /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1263 PyObject *
1264 PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1266 PyTypeObject *tp = Py_TYPE(obj);
1267 PyObject *descr = NULL;
1268 PyObject *res = NULL;
1269 descrgetfunc f;
1270 Py_ssize_t dictoffset;
1271 PyObject **dictptr;
1273 if (!PyString_Check(name)){
1274 #ifdef Py_USING_UNICODE
1275 /* The Unicode to string conversion is done here because the
1276 existing tp_setattro slots expect a string object as name
1277 and we wouldn't want to break those. */
1278 if (PyUnicode_Check(name)) {
1279 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1280 if (name == NULL)
1281 return NULL;
1283 else
1284 #endif
1286 PyErr_Format(PyExc_TypeError,
1287 "attribute name must be string, not '%.200s'",
1288 Py_TYPE(name)->tp_name);
1289 return NULL;
1292 else
1293 Py_INCREF(name);
1295 if (tp->tp_dict == NULL) {
1296 if (PyType_Ready(tp) < 0)
1297 goto done;
1300 #if 0 /* XXX this is not quite _PyType_Lookup anymore */
1301 /* Inline _PyType_Lookup */
1303 Py_ssize_t i, n;
1304 PyObject *mro, *base, *dict;
1306 /* Look in tp_dict of types in MRO */
1307 mro = tp->tp_mro;
1308 assert(mro != NULL);
1309 assert(PyTuple_Check(mro));
1310 n = PyTuple_GET_SIZE(mro);
1311 for (i = 0; i < n; i++) {
1312 base = PyTuple_GET_ITEM(mro, i);
1313 if (PyClass_Check(base))
1314 dict = ((PyClassObject *)base)->cl_dict;
1315 else {
1316 assert(PyType_Check(base));
1317 dict = ((PyTypeObject *)base)->tp_dict;
1319 assert(dict && PyDict_Check(dict));
1320 descr = PyDict_GetItem(dict, name);
1321 if (descr != NULL)
1322 break;
1325 #else
1326 descr = _PyType_Lookup(tp, name);
1327 #endif
1329 Py_XINCREF(descr);
1331 f = NULL;
1332 if (descr != NULL &&
1333 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1334 f = descr->ob_type->tp_descr_get;
1335 if (f != NULL && PyDescr_IsData(descr)) {
1336 res = f(descr, obj, (PyObject *)obj->ob_type);
1337 Py_DECREF(descr);
1338 goto done;
1342 /* Inline _PyObject_GetDictPtr */
1343 dictoffset = tp->tp_dictoffset;
1344 if (dictoffset != 0) {
1345 PyObject *dict;
1346 if (dictoffset < 0) {
1347 Py_ssize_t tsize;
1348 size_t size;
1350 tsize = ((PyVarObject *)obj)->ob_size;
1351 if (tsize < 0)
1352 tsize = -tsize;
1353 size = _PyObject_VAR_SIZE(tp, tsize);
1355 dictoffset += (long)size;
1356 assert(dictoffset > 0);
1357 assert(dictoffset % SIZEOF_VOID_P == 0);
1359 dictptr = (PyObject **) ((char *)obj + dictoffset);
1360 dict = *dictptr;
1361 if (dict != NULL) {
1362 Py_INCREF(dict);
1363 res = PyDict_GetItem(dict, name);
1364 if (res != NULL) {
1365 Py_INCREF(res);
1366 Py_XDECREF(descr);
1367 Py_DECREF(dict);
1368 goto done;
1370 Py_DECREF(dict);
1374 if (f != NULL) {
1375 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1376 Py_DECREF(descr);
1377 goto done;
1380 if (descr != NULL) {
1381 res = descr;
1382 /* descr was already increfed above */
1383 goto done;
1386 PyErr_Format(PyExc_AttributeError,
1387 "'%.50s' object has no attribute '%.400s'",
1388 tp->tp_name, PyString_AS_STRING(name));
1389 done:
1390 Py_DECREF(name);
1391 return res;
1395 PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1397 PyTypeObject *tp = Py_TYPE(obj);
1398 PyObject *descr;
1399 descrsetfunc f;
1400 PyObject **dictptr;
1401 int res = -1;
1403 if (!PyString_Check(name)){
1404 #ifdef Py_USING_UNICODE
1405 /* The Unicode to string conversion is done here because the
1406 existing tp_setattro slots expect a string object as name
1407 and we wouldn't want to break those. */
1408 if (PyUnicode_Check(name)) {
1409 name = PyUnicode_AsEncodedString(name, NULL, NULL);
1410 if (name == NULL)
1411 return -1;
1413 else
1414 #endif
1416 PyErr_Format(PyExc_TypeError,
1417 "attribute name must be string, not '%.200s'",
1418 Py_TYPE(name)->tp_name);
1419 return -1;
1422 else
1423 Py_INCREF(name);
1425 if (tp->tp_dict == NULL) {
1426 if (PyType_Ready(tp) < 0)
1427 goto done;
1430 descr = _PyType_Lookup(tp, name);
1431 f = NULL;
1432 if (descr != NULL &&
1433 PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1434 f = descr->ob_type->tp_descr_set;
1435 if (f != NULL && PyDescr_IsData(descr)) {
1436 res = f(descr, obj, value);
1437 goto done;
1441 dictptr = _PyObject_GetDictPtr(obj);
1442 if (dictptr != NULL) {
1443 PyObject *dict = *dictptr;
1444 if (dict == NULL && value != NULL) {
1445 dict = PyDict_New();
1446 if (dict == NULL)
1447 goto done;
1448 *dictptr = dict;
1450 if (dict != NULL) {
1451 Py_INCREF(dict);
1452 if (value == NULL)
1453 res = PyDict_DelItem(dict, name);
1454 else
1455 res = PyDict_SetItem(dict, name, value);
1456 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1457 PyErr_SetObject(PyExc_AttributeError, name);
1458 Py_DECREF(dict);
1459 goto done;
1463 if (f != NULL) {
1464 res = f(descr, obj, value);
1465 goto done;
1468 if (descr == NULL) {
1469 PyErr_Format(PyExc_AttributeError,
1470 "'%.100s' object has no attribute '%.200s'",
1471 tp->tp_name, PyString_AS_STRING(name));
1472 goto done;
1475 PyErr_Format(PyExc_AttributeError,
1476 "'%.50s' object attribute '%.400s' is read-only",
1477 tp->tp_name, PyString_AS_STRING(name));
1478 done:
1479 Py_DECREF(name);
1480 return res;
1483 /* Test a value used as condition, e.g., in a for or if statement.
1484 Return -1 if an error occurred */
1487 PyObject_IsTrue(PyObject *v)
1489 Py_ssize_t res;
1490 if (v == Py_True)
1491 return 1;
1492 if (v == Py_False)
1493 return 0;
1494 if (v == Py_None)
1495 return 0;
1496 else if (v->ob_type->tp_as_number != NULL &&
1497 v->ob_type->tp_as_number->nb_nonzero != NULL)
1498 res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
1499 else if (v->ob_type->tp_as_mapping != NULL &&
1500 v->ob_type->tp_as_mapping->mp_length != NULL)
1501 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1502 else if (v->ob_type->tp_as_sequence != NULL &&
1503 v->ob_type->tp_as_sequence->sq_length != NULL)
1504 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1505 else
1506 return 1;
1507 /* if it is negative, it should be either -1 or -2 */
1508 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
1511 /* equivalent of 'not v'
1512 Return -1 if an error occurred */
1515 PyObject_Not(PyObject *v)
1517 int res;
1518 res = PyObject_IsTrue(v);
1519 if (res < 0)
1520 return res;
1521 return res == 0;
1524 /* Coerce two numeric types to the "larger" one.
1525 Increment the reference count on each argument.
1526 Return value:
1527 -1 if an error occurred;
1528 0 if the coercion succeeded (and then the reference counts are increased);
1529 1 if no coercion is possible (and no error is raised).
1532 PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
1534 register PyObject *v = *pv;
1535 register PyObject *w = *pw;
1536 int res;
1538 /* Shortcut only for old-style types */
1539 if (v->ob_type == w->ob_type &&
1540 !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1542 Py_INCREF(v);
1543 Py_INCREF(w);
1544 return 0;
1546 if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1547 res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1548 if (res <= 0)
1549 return res;
1551 if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1552 res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1553 if (res <= 0)
1554 return res;
1556 return 1;
1559 /* Coerce two numeric types to the "larger" one.
1560 Increment the reference count on each argument.
1561 Return -1 and raise an exception if no coercion is possible
1562 (and then no reference count is incremented).
1565 PyNumber_Coerce(PyObject **pv, PyObject **pw)
1567 int err = PyNumber_CoerceEx(pv, pw);
1568 if (err <= 0)
1569 return err;
1570 PyErr_SetString(PyExc_TypeError, "number coercion failed");
1571 return -1;
1575 /* Test whether an object can be called */
1578 PyCallable_Check(PyObject *x)
1580 if (x == NULL)
1581 return 0;
1582 if (PyInstance_Check(x)) {
1583 PyObject *call = PyObject_GetAttrString(x, "__call__");
1584 if (call == NULL) {
1585 PyErr_Clear();
1586 return 0;
1588 /* Could test recursively but don't, for fear of endless
1589 recursion if some joker sets self.__call__ = self */
1590 Py_DECREF(call);
1591 return 1;
1593 else {
1594 return x->ob_type->tp_call != NULL;
1598 /* ------------------------- PyObject_Dir() helpers ------------------------- */
1600 /* Helper for PyObject_Dir.
1601 Merge the __dict__ of aclass into dict, and recursively also all
1602 the __dict__s of aclass's base classes. The order of merging isn't
1603 defined, as it's expected that only the final set of dict keys is
1604 interesting.
1605 Return 0 on success, -1 on error.
1608 static int
1609 merge_class_dict(PyObject* dict, PyObject* aclass)
1611 PyObject *classdict;
1612 PyObject *bases;
1614 assert(PyDict_Check(dict));
1615 assert(aclass);
1617 /* Merge in the type's dict (if any). */
1618 classdict = PyObject_GetAttrString(aclass, "__dict__");
1619 if (classdict == NULL)
1620 PyErr_Clear();
1621 else {
1622 int status = PyDict_Update(dict, classdict);
1623 Py_DECREF(classdict);
1624 if (status < 0)
1625 return -1;
1628 /* Recursively merge in the base types' (if any) dicts. */
1629 bases = PyObject_GetAttrString(aclass, "__bases__");
1630 if (bases == NULL)
1631 PyErr_Clear();
1632 else {
1633 /* We have no guarantee that bases is a real tuple */
1634 Py_ssize_t i, n;
1635 n = PySequence_Size(bases); /* This better be right */
1636 if (n < 0)
1637 PyErr_Clear();
1638 else {
1639 for (i = 0; i < n; i++) {
1640 int status;
1641 PyObject *base = PySequence_GetItem(bases, i);
1642 if (base == NULL) {
1643 Py_DECREF(bases);
1644 return -1;
1646 status = merge_class_dict(dict, base);
1647 Py_DECREF(base);
1648 if (status < 0) {
1649 Py_DECREF(bases);
1650 return -1;
1654 Py_DECREF(bases);
1656 return 0;
1659 /* Helper for PyObject_Dir.
1660 If obj has an attr named attrname that's a list, merge its string
1661 elements into keys of dict.
1662 Return 0 on success, -1 on error. Errors due to not finding the attr,
1663 or the attr not being a list, are suppressed.
1666 static int
1667 merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
1669 PyObject *list;
1670 int result = 0;
1672 assert(PyDict_Check(dict));
1673 assert(obj);
1674 assert(attrname);
1676 list = PyObject_GetAttrString(obj, attrname);
1677 if (list == NULL)
1678 PyErr_Clear();
1680 else if (PyList_Check(list)) {
1681 int i;
1682 for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1683 PyObject *item = PyList_GET_ITEM(list, i);
1684 if (PyString_Check(item)) {
1685 result = PyDict_SetItem(dict, item, Py_None);
1686 if (result < 0)
1687 break;
1692 Py_XDECREF(list);
1693 return result;
1696 /* Helper for PyObject_Dir without arguments: returns the local scope. */
1697 static PyObject *
1698 _dir_locals(void)
1700 PyObject *names;
1701 PyObject *locals = PyEval_GetLocals();
1703 if (locals == NULL) {
1704 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1705 return NULL;
1708 names = PyMapping_Keys(locals);
1709 if (!names)
1710 return NULL;
1711 if (!PyList_Check(names)) {
1712 PyErr_Format(PyExc_TypeError,
1713 "dir(): expected keys() of locals to be a list, "
1714 "not '%.200s'", Py_TYPE(names)->tp_name);
1715 Py_DECREF(names);
1716 return NULL;
1718 /* the locals don't need to be DECREF'd */
1719 return names;
1722 /* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
1723 We deliberately don't suck up its __class__, as methods belonging to the
1724 metaclass would probably be more confusing than helpful.
1726 static PyObject *
1727 _specialized_dir_type(PyObject *obj)
1729 PyObject *result = NULL;
1730 PyObject *dict = PyDict_New();
1732 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1733 result = PyDict_Keys(dict);
1735 Py_XDECREF(dict);
1736 return result;
1739 /* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1740 static PyObject *
1741 _specialized_dir_module(PyObject *obj)
1743 PyObject *result = NULL;
1744 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
1746 if (dict != NULL) {
1747 if (PyDict_Check(dict))
1748 result = PyDict_Keys(dict);
1749 else {
1750 PyErr_Format(PyExc_TypeError,
1751 "%.200s.__dict__ is not a dictionary",
1752 PyModule_GetName(obj));
1756 Py_XDECREF(dict);
1757 return result;
1760 /* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1761 and recursively up the __class__.__bases__ chain.
1763 static PyObject *
1764 _generic_dir(PyObject *obj)
1766 PyObject *result = NULL;
1767 PyObject *dict = NULL;
1768 PyObject *itsclass = NULL;
1770 /* Get __dict__ (which may or may not be a real dict...) */
1771 dict = PyObject_GetAttrString(obj, "__dict__");
1772 if (dict == NULL) {
1773 PyErr_Clear();
1774 dict = PyDict_New();
1776 else if (!PyDict_Check(dict)) {
1777 Py_DECREF(dict);
1778 dict = PyDict_New();
1780 else {
1781 /* Copy __dict__ to avoid mutating it. */
1782 PyObject *temp = PyDict_Copy(dict);
1783 Py_DECREF(dict);
1784 dict = temp;
1787 if (dict == NULL)
1788 goto error;
1790 /* Merge in __members__ and __methods__ (if any).
1791 * This is removed in Python 3000. */
1792 if (merge_list_attr(dict, obj, "__members__") < 0)
1793 goto error;
1794 if (merge_list_attr(dict, obj, "__methods__") < 0)
1795 goto error;
1797 /* Merge in attrs reachable from its class. */
1798 itsclass = PyObject_GetAttrString(obj, "__class__");
1799 if (itsclass == NULL)
1800 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1801 __class__ exists? */
1802 PyErr_Clear();
1803 else {
1804 if (merge_class_dict(dict, itsclass) != 0)
1805 goto error;
1808 result = PyDict_Keys(dict);
1809 /* fall through */
1810 error:
1811 Py_XDECREF(itsclass);
1812 Py_XDECREF(dict);
1813 return result;
1816 /* Helper for PyObject_Dir: object introspection.
1817 This calls one of the above specialized versions if no __dir__ method
1818 exists. */
1819 static PyObject *
1820 _dir_object(PyObject *obj)
1822 PyObject *result = NULL;
1823 PyObject *dirfunc = PyObject_GetAttrString((PyObject *)obj->ob_type,
1824 "__dir__");
1826 assert(obj);
1827 if (dirfunc == NULL) {
1828 /* use default implementation */
1829 PyErr_Clear();
1830 if (PyModule_Check(obj))
1831 result = _specialized_dir_module(obj);
1832 else if (PyType_Check(obj) || PyClass_Check(obj))
1833 result = _specialized_dir_type(obj);
1834 else
1835 result = _generic_dir(obj);
1837 else {
1838 /* use __dir__ */
1839 result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
1840 Py_DECREF(dirfunc);
1841 if (result == NULL)
1842 return NULL;
1844 /* result must be a list */
1845 /* XXX(gbrandl): could also check if all items are strings */
1846 if (!PyList_Check(result)) {
1847 PyErr_Format(PyExc_TypeError,
1848 "__dir__() must return a list, not %.200s",
1849 Py_TYPE(result)->tp_name);
1850 Py_DECREF(result);
1851 result = NULL;
1855 return result;
1858 /* Implementation of dir() -- if obj is NULL, returns the names in the current
1859 (local) scope. Otherwise, performs introspection of the object: returns a
1860 sorted list of attribute names (supposedly) accessible from the object
1862 PyObject *
1863 PyObject_Dir(PyObject *obj)
1865 PyObject * result;
1867 if (obj == NULL)
1868 /* no object -- introspect the locals */
1869 result = _dir_locals();
1870 else
1871 /* object -- introspect the object */
1872 result = _dir_object(obj);
1874 assert(result == NULL || PyList_Check(result));
1876 if (result != NULL && PyList_Sort(result) != 0) {
1877 /* sorting the list failed */
1878 Py_DECREF(result);
1879 result = NULL;
1882 return result;
1886 NoObject is usable as a non-NULL undefined value, used by the macro None.
1887 There is (and should be!) no way to create other objects of this type,
1888 so there is exactly one (which is indestructible, by the way).
1889 (XXX This type and the type of NotImplemented below should be unified.)
1892 /* ARGSUSED */
1893 static PyObject *
1894 none_repr(PyObject *op)
1896 return PyString_FromString("None");
1899 /* ARGUSED */
1900 static void
1901 none_dealloc(PyObject* ignore)
1903 /* This should never get called, but we also don't want to SEGV if
1904 * we accidently decref None out of existance.
1906 Py_FatalError("deallocating None");
1910 static PyTypeObject PyNone_Type = {
1911 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1912 "NoneType",
1915 none_dealloc, /*tp_dealloc*/ /*never called*/
1916 0, /*tp_print*/
1917 0, /*tp_getattr*/
1918 0, /*tp_setattr*/
1919 0, /*tp_compare*/
1920 none_repr, /*tp_repr*/
1921 0, /*tp_as_number*/
1922 0, /*tp_as_sequence*/
1923 0, /*tp_as_mapping*/
1924 (hashfunc)_Py_HashPointer, /*tp_hash */
1927 PyObject _Py_NoneStruct = {
1928 _PyObject_EXTRA_INIT
1929 1, &PyNone_Type
1932 /* NotImplemented is an object that can be used to signal that an
1933 operation is not implemented for the given type combination. */
1935 static PyObject *
1936 NotImplemented_repr(PyObject *op)
1938 return PyString_FromString("NotImplemented");
1941 static PyTypeObject PyNotImplemented_Type = {
1942 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1943 "NotImplementedType",
1946 none_dealloc, /*tp_dealloc*/ /*never called*/
1947 0, /*tp_print*/
1948 0, /*tp_getattr*/
1949 0, /*tp_setattr*/
1950 0, /*tp_compare*/
1951 NotImplemented_repr, /*tp_repr*/
1952 0, /*tp_as_number*/
1953 0, /*tp_as_sequence*/
1954 0, /*tp_as_mapping*/
1955 0, /*tp_hash */
1958 PyObject _Py_NotImplementedStruct = {
1959 _PyObject_EXTRA_INIT
1960 1, &PyNotImplemented_Type
1963 void
1964 _Py_ReadyTypes(void)
1966 if (PyType_Ready(&PyType_Type) < 0)
1967 Py_FatalError("Can't initialize 'type'");
1969 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1970 Py_FatalError("Can't initialize 'weakref'");
1972 if (PyType_Ready(&PyBool_Type) < 0)
1973 Py_FatalError("Can't initialize 'bool'");
1975 if (PyType_Ready(&PyString_Type) < 0)
1976 Py_FatalError("Can't initialize 'str'");
1978 if (PyType_Ready(&PyList_Type) < 0)
1979 Py_FatalError("Can't initialize 'list'");
1981 if (PyType_Ready(&PyNone_Type) < 0)
1982 Py_FatalError("Can't initialize type(None)");
1984 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1985 Py_FatalError("Can't initialize type(NotImplemented)");
1989 #ifdef Py_TRACE_REFS
1991 void
1992 _Py_NewReference(PyObject *op)
1994 _Py_INC_REFTOTAL;
1995 op->ob_refcnt = 1;
1996 _Py_AddToAllObjects(op, 1);
1997 _Py_INC_TPALLOCS(op);
2000 void
2001 _Py_ForgetReference(register PyObject *op)
2003 #ifdef SLOW_UNREF_CHECK
2004 register PyObject *p;
2005 #endif
2006 if (op->ob_refcnt < 0)
2007 Py_FatalError("UNREF negative refcnt");
2008 if (op == &refchain ||
2009 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
2010 Py_FatalError("UNREF invalid object");
2011 #ifdef SLOW_UNREF_CHECK
2012 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
2013 if (p == op)
2014 break;
2016 if (p == &refchain) /* Not found */
2017 Py_FatalError("UNREF unknown object");
2018 #endif
2019 op->_ob_next->_ob_prev = op->_ob_prev;
2020 op->_ob_prev->_ob_next = op->_ob_next;
2021 op->_ob_next = op->_ob_prev = NULL;
2022 _Py_INC_TPFREES(op);
2025 void
2026 _Py_Dealloc(PyObject *op)
2028 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2029 _Py_ForgetReference(op);
2030 (*dealloc)(op);
2033 /* Print all live objects. Because PyObject_Print is called, the
2034 * interpreter must be in a healthy state.
2036 void
2037 _Py_PrintReferences(FILE *fp)
2039 PyObject *op;
2040 fprintf(fp, "Remaining objects:\n");
2041 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
2042 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
2043 if (PyObject_Print(op, fp, 0) != 0)
2044 PyErr_Clear();
2045 putc('\n', fp);
2049 /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
2050 * doesn't make any calls to the Python C API, so is always safe to call.
2052 void
2053 _Py_PrintReferenceAddresses(FILE *fp)
2055 PyObject *op;
2056 fprintf(fp, "Remaining object addresses:\n");
2057 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
2058 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
2059 op->ob_refcnt, Py_TYPE(op)->tp_name);
2062 PyObject *
2063 _Py_GetObjects(PyObject *self, PyObject *args)
2065 int i, n;
2066 PyObject *t = NULL;
2067 PyObject *res, *op;
2069 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2070 return NULL;
2071 op = refchain._ob_next;
2072 res = PyList_New(0);
2073 if (res == NULL)
2074 return NULL;
2075 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2076 while (op == self || op == args || op == res || op == t ||
2077 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2078 op = op->_ob_next;
2079 if (op == &refchain)
2080 return res;
2082 if (PyList_Append(res, op) < 0) {
2083 Py_DECREF(res);
2084 return NULL;
2086 op = op->_ob_next;
2088 return res;
2091 #endif
2094 /* Hack to force loading of cobject.o */
2095 PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
2098 /* Hack to force loading of abstract.o */
2099 Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
2102 /* Python's malloc wrappers (see pymem.h) */
2104 void *
2105 PyMem_Malloc(size_t nbytes)
2107 return PyMem_MALLOC(nbytes);
2110 void *
2111 PyMem_Realloc(void *p, size_t nbytes)
2113 return PyMem_REALLOC(p, nbytes);
2116 void
2117 PyMem_Free(void *p)
2119 PyMem_FREE(p);
2123 /* These methods are used to control infinite recursion in repr, str, print,
2124 etc. Container objects that may recursively contain themselves,
2125 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2126 Py_ReprLeave() to avoid infinite recursion.
2128 Py_ReprEnter() returns 0 the first time it is called for a particular
2129 object and 1 every time thereafter. It returns -1 if an exception
2130 occurred. Py_ReprLeave() has no return value.
2132 See dictobject.c and listobject.c for examples of use.
2135 #define KEY "Py_Repr"
2138 Py_ReprEnter(PyObject *obj)
2140 PyObject *dict;
2141 PyObject *list;
2142 Py_ssize_t i;
2144 dict = PyThreadState_GetDict();
2145 if (dict == NULL)
2146 return 0;
2147 list = PyDict_GetItemString(dict, KEY);
2148 if (list == NULL) {
2149 list = PyList_New(0);
2150 if (list == NULL)
2151 return -1;
2152 if (PyDict_SetItemString(dict, KEY, list) < 0)
2153 return -1;
2154 Py_DECREF(list);
2156 i = PyList_GET_SIZE(list);
2157 while (--i >= 0) {
2158 if (PyList_GET_ITEM(list, i) == obj)
2159 return 1;
2161 PyList_Append(list, obj);
2162 return 0;
2165 void
2166 Py_ReprLeave(PyObject *obj)
2168 PyObject *dict;
2169 PyObject *list;
2170 Py_ssize_t i;
2172 dict = PyThreadState_GetDict();
2173 if (dict == NULL)
2174 return;
2175 list = PyDict_GetItemString(dict, KEY);
2176 if (list == NULL || !PyList_Check(list))
2177 return;
2178 i = PyList_GET_SIZE(list);
2179 /* Count backwards because we always expect obj to be list[-1] */
2180 while (--i >= 0) {
2181 if (PyList_GET_ITEM(list, i) == obj) {
2182 PyList_SetSlice(list, i, i + 1, NULL);
2183 break;
2188 /* Trashcan support. */
2190 /* Current call-stack depth of tp_dealloc calls. */
2191 int _PyTrash_delete_nesting = 0;
2193 /* List of objects that still need to be cleaned up, singly linked via their
2194 * gc headers' gc_prev pointers.
2196 PyObject *_PyTrash_delete_later = NULL;
2198 /* Add op to the _PyTrash_delete_later list. Called when the current
2199 * call-stack depth gets large. op must be a currently untracked gc'ed
2200 * object, with refcount 0. Py_DECREF must already have been called on it.
2202 void
2203 _PyTrash_deposit_object(PyObject *op)
2205 assert(PyObject_IS_GC(op));
2206 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2207 assert(op->ob_refcnt == 0);
2208 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2209 _PyTrash_delete_later = op;
2212 /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2213 * the call-stack unwinds again.
2215 void
2216 _PyTrash_destroy_chain(void)
2218 while (_PyTrash_delete_later) {
2219 PyObject *op = _PyTrash_delete_later;
2220 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2222 _PyTrash_delete_later =
2223 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2225 /* Call the deallocator directly. This used to try to
2226 * fool Py_DECREF into calling it indirectly, but
2227 * Py_DECREF was already called on this object, and in
2228 * assorted non-release builds calling Py_DECREF again ends
2229 * up distorting allocation statistics.
2231 assert(op->ob_refcnt == 0);
2232 ++_PyTrash_delete_nesting;
2233 (*dealloc)(op);
2234 --_PyTrash_delete_nesting;
2238 #ifdef __cplusplus
2240 #endif