cpython/Objects/object.c

2141 lines
50 KiB
C
Raw Normal View History

1991-02-19 08:39:46 -04:00
1990-12-20 11:06:42 -04:00
/* Generic object operations; and implementation of None (NoObject) */
1990-10-14 09:07:46 -03:00
1997-05-02 00:12:38 -03:00
#include "Python.h"
1990-10-14 09:07:46 -03:00
#ifdef __cplusplus
extern "C" {
#endif
#ifdef Py_REF_DEBUG
Py_ssize_t _Py_RefTotal;
Py_ssize_t
_Py_GetRefTotal(void)
{
PyObject *o;
Py_ssize_t total = _Py_RefTotal;
/* ignore the references to the dummy object of the dicts and sets
because they are not reliable and not useful (now that the
hash table code is well-tested) */
o = _PyDict_Dummy();
if (o != NULL)
total -= o->ob_refcnt;
o = _PySet_Dummy();
if (o != NULL)
total -= o->ob_refcnt;
return total;
}
#endif /* Py_REF_DEBUG */
1990-10-14 09:07:46 -03:00
int Py_DivisionWarningFlag;
Add warning mode for classic division, almost exactly as specified in PEP 238. Changes: - add a new flag variable Py_DivisionWarningFlag, declared in pydebug.h, defined in object.c, set in main.c, and used in {int,long,float,complex}object.c. When this flag is set, the classic division operator issues a DeprecationWarning message. - add a new API PyRun_SimpleStringFlags() to match PyRun_SimpleString(). The main() function calls this so that commands run with -c can also benefit from -Dnew. - While I was at it, I changed the usage message in main() somewhat: alphabetized the options, split it in *four* parts to fit in under 512 bytes (not that I still believe this is necessary -- doc strings elsewhere are much longer), and perhaps most visibly, don't display the full list of options on each command line error. Instead, the full list is only displayed when -h is used, and otherwise a brief reminder of -h is displayed. When -h is used, write to stdout so that you can do `python -h | more'. Notes: - I don't want to use the -W option to control whether the classic division warning is issued or not, because the machinery to decide whether to display the warning or not is very expensive (it involves calling into the warnings.py module). You can use -Werror to turn the warnings into exceptions though. - The -Dnew option doesn't select future division for all of the program -- only for the __main__ module. I don't know if I'll ever change this -- it would require changes to the .pyc file magic number to do it right, and a more global notion of compiler flags. - You can usefully combine -Dwarn and -Dnew: this gives the __main__ module new division, and warns about classic division everywhere else.
2001-08-31 14:40:15 -03:00
1990-12-20 11:06:42 -04:00
/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
These are used by the individual routines for object creation.
Do not call them otherwise, they do not initialize the object! */
1990-10-14 09:07:46 -03:00
#ifdef Py_TRACE_REFS
/* Head of circular doubly-linked list of all objects. These are linked
* together via the _ob_prev and _ob_next members of a PyObject, which
* exist only in a Py_TRACE_REFS build.
*/
static PyObject refchain = {&refchain, &refchain};
/* Insert op at the front of the list of all objects. If force is true,
* op is added even if _ob_prev and _ob_next are non-NULL already. If
* force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
* force should be true if and only if op points to freshly allocated,
* uninitialized memory, or you've unlinked op from the list and are
2003-03-23 14:06:08 -04:00
* relinking it into the front.
* Note that objects are normally added to the list via _Py_NewReference,
* which is called by PyObject_Init. Not all objects are initialized that
* way, though; exceptions include statically allocated type objects, and
* statically allocated singletons (like Py_True and Py_None).
*/
void
_Py_AddToAllObjects(PyObject *op, int force)
{
#ifdef Py_DEBUG
if (!force) {
/* If it's initialized memory, op must be in or out of
* the list unambiguously.
*/
assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
}
#endif
if (force || op->_ob_prev == NULL) {
op->_ob_next = refchain._ob_next;
op->_ob_prev = &refchain;
refchain._ob_next->_ob_prev = op;
refchain._ob_next = op;
}
}
#endif /* Py_TRACE_REFS */
#ifdef COUNT_ALLOCS
1997-05-02 00:12:38 -03:00
static PyTypeObject *type_list;
/* All types are added to type_list, at least when
they get one object created. That makes them
immortal, which unfortunately contributes to
garbage itself. If unlist_types_without_objects
is set, they will be removed from the type_list
once the last object is deallocated. */
int unlist_types_without_objects;
extern int tuple_zero_allocs, fast_tuple_allocs;
extern int quick_int_allocs, quick_neg_int_allocs;
extern int null_strings, one_strings;
void
dump_counts(FILE* f)
{
1997-05-02 00:12:38 -03:00
PyTypeObject *tp;
for (tp = type_list; tp; tp = tp->tp_next)
fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",
2001-08-02 01:15:00 -03:00
tp->tp_name, tp->tp_allocs, tp->tp_frees,
tp->tp_maxalloc);
fprintf(f, "fast tuple allocs: %d, empty: %d\n",
fast_tuple_allocs, tuple_zero_allocs);
fprintf(f, "fast int allocs: pos: %d, neg: %d\n",
quick_int_allocs, quick_neg_int_allocs);
fprintf(f, "null strings: %d, 1-strings: %d\n",
null_strings, one_strings);
}
PyObject *
2000-07-09 12:48:49 -03:00
get_counts(void)
{
PyTypeObject *tp;
PyObject *result;
PyObject *v;
result = PyList_New(0);
if (result == NULL)
return NULL;
for (tp = type_list; tp; tp = tp->tp_next) {
Partially merge trunk into p3yk. The removal of Mac/Tools is confusing svn merge in bad ways, so I'll have to merge that extra-carefully (probably manually.) Merged revisions 46495-46605 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r46495 | tim.peters | 2006-05-28 03:52:38 +0200 (Sun, 28 May 2006) | 2 lines Added missing svn:eol-style property to text files. ........ r46497 | tim.peters | 2006-05-28 12:41:29 +0200 (Sun, 28 May 2006) | 3 lines PyErr_Display(), PyErr_WriteUnraisable(): Coverity found a cut-and-paste bug in both: `className` was referenced before being checked for NULL. ........ r46499 | fredrik.lundh | 2006-05-28 14:06:46 +0200 (Sun, 28 May 2006) | 5 lines needforspeed: added Py_MEMCPY macro (currently tuned for Visual C only), and use it for string copy operations. this gives a 20% speedup on some string benchmarks. ........ r46501 | michael.hudson | 2006-05-28 17:51:40 +0200 (Sun, 28 May 2006) | 26 lines Quality control, meet exceptions.c. Fix a number of problems with the need for speed code: One is doing this sort of thing: Py_DECREF(self->field); self->field = newval; Py_INCREF(self->field); without being very sure that self->field doesn't start with a value that has a __del__, because that almost certainly can lead to segfaults. As self->args is constrained to be an exact tuple we may as well exploit this fact consistently. This leads to quite a lot of simplification (and, hey, probably better performance). Add some error checking in places lacking it. Fix some rather strange indentation in the Unicode code. Delete some trailing whitespace. More to come, I haven't fixed all the reference leaks yet... ........ r46502 | george.yoshida | 2006-05-28 18:39:09 +0200 (Sun, 28 May 2006) | 3 lines Patch #1080727: add "encoding" parameter to doctest.DocFileSuite Contributed by Bjorn Tillenius. ........ r46503 | martin.v.loewis | 2006-05-28 18:57:38 +0200 (Sun, 28 May 2006) | 4 lines Rest of patch #1490384: Commit icon source, remove claim that Erik von Blokland is the author of the installer picture. ........ r46504 | michael.hudson | 2006-05-28 19:40:29 +0200 (Sun, 28 May 2006) | 16 lines Quality control, meet exceptions.c, round two. Make some functions that should have been static static. Fix a bunch of refleaks by fixing the definition of MiddlingExtendsException. Remove all the __new__ implementations apart from BaseException_new. Rewrite most code that needs it to cope with NULL fields (such code could get excercised anyway, the __new__-removal just makes it more likely). This involved editing the code for WindowsError, which I can't test. This fixes all the refleaks in at least the start of a regrtest -R :: run. ........ r46505 | marc-andre.lemburg | 2006-05-28 19:46:58 +0200 (Sun, 28 May 2006) | 10 lines Initial version of systimes - a module to provide platform dependent performance measurements. The module is currently just a proof-of-concept implementation, but will integrated into pybench once it is stable enough. License: pybench license. Author: Marc-Andre Lemburg. ........ r46507 | armin.rigo | 2006-05-28 21:13:17 +0200 (Sun, 28 May 2006) | 15 lines ("Forward-port" of r46506) Remove various dependencies on dictionary order in the standard library tests, and one (clearly an oversight, potentially critical) in the standard library itself - base64.py. Remaining open issues: * test_extcall is an output test, messy to make robust * tarfile.py has a potential bug here, but I'm not familiar enough with this code. Filed in as SF bug #1496501. * urllib2.HTTPPasswordMgr() returns a random result if there is more than one matching root path. I'm asking python-dev for clarification... ........ r46508 | georg.brandl | 2006-05-28 22:11:45 +0200 (Sun, 28 May 2006) | 4 lines The empty string is a valid import path. (fixes #1496539) ........ r46509 | georg.brandl | 2006-05-28 22:23:12 +0200 (Sun, 28 May 2006) | 3 lines Patch #1496206: urllib2 PasswordMgr ./. default ports ........ r46510 | georg.brandl | 2006-05-28 22:57:09 +0200 (Sun, 28 May 2006) | 3 lines Fix refleaks in UnicodeError get and set methods. ........ r46511 | michael.hudson | 2006-05-28 23:19:03 +0200 (Sun, 28 May 2006) | 3 lines use the UnicodeError traversal and clearing functions in UnicodeError subclasses. ........ r46512 | thomas.wouters | 2006-05-28 23:32:12 +0200 (Sun, 28 May 2006) | 4 lines Make last patch valid C89 so Windows compilers can deal with it. ........ r46513 | georg.brandl | 2006-05-28 23:42:54 +0200 (Sun, 28 May 2006) | 3 lines Fix ref-antileak in _struct.c which eventually lead to deallocating None. ........ r46514 | georg.brandl | 2006-05-28 23:57:35 +0200 (Sun, 28 May 2006) | 4 lines Correct None refcount issue in Mac modules. (Are they still used?) ........ r46515 | armin.rigo | 2006-05-29 00:07:08 +0200 (Mon, 29 May 2006) | 3 lines A clearer error message when passing -R to regrtest.py with release builds of Python. ........ r46516 | georg.brandl | 2006-05-29 00:14:04 +0200 (Mon, 29 May 2006) | 3 lines Fix C function calling conventions in _sre module. ........ r46517 | georg.brandl | 2006-05-29 00:34:51 +0200 (Mon, 29 May 2006) | 3 lines Convert audioop over to METH_VARARGS. ........ r46518 | georg.brandl | 2006-05-29 00:38:57 +0200 (Mon, 29 May 2006) | 3 lines METH_NOARGS functions do get called with two args. ........ r46519 | georg.brandl | 2006-05-29 11:46:51 +0200 (Mon, 29 May 2006) | 4 lines Fix refleak in socketmodule. Replace bogus Py_BuildValue calls. Fix refleak in exceptions. ........ r46520 | nick.coghlan | 2006-05-29 14:43:05 +0200 (Mon, 29 May 2006) | 7 lines Apply modified version of Collin Winter's patch #1478788 Renames functional extension module to _functools and adds a Python functools module so that utility functions like update_wrapper can be added easily. ........ r46522 | georg.brandl | 2006-05-29 15:53:16 +0200 (Mon, 29 May 2006) | 3 lines Convert fmmodule to METH_VARARGS. ........ r46523 | georg.brandl | 2006-05-29 16:13:21 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494605. ........ r46524 | georg.brandl | 2006-05-29 16:28:05 +0200 (Mon, 29 May 2006) | 3 lines Handle PyMem_Malloc failure in pystrtod.c. Closes #1494671. ........ r46525 | georg.brandl | 2006-05-29 16:33:55 +0200 (Mon, 29 May 2006) | 3 lines Fix compiler warning. ........ r46526 | georg.brandl | 2006-05-29 16:39:00 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494787 (pyclbr counts whitespace as superclass name) ........ r46527 | bob.ippolito | 2006-05-29 17:47:29 +0200 (Mon, 29 May 2006) | 1 line simplify the struct code a bit (no functional changes) ........ r46528 | armin.rigo | 2006-05-29 19:59:47 +0200 (Mon, 29 May 2006) | 2 lines Silence a warning. ........ r46529 | georg.brandl | 2006-05-29 21:39:45 +0200 (Mon, 29 May 2006) | 3 lines Correct some value converting strangenesses. ........ r46530 | nick.coghlan | 2006-05-29 22:27:44 +0200 (Mon, 29 May 2006) | 1 line When adding a module like functools, it helps to let SVN know about the file. ........ r46531 | georg.brandl | 2006-05-29 22:52:54 +0200 (Mon, 29 May 2006) | 4 lines Patches #1497027 and #972322: try HTTP digest auth first, and watch out for handler name collisions. ........ r46532 | georg.brandl | 2006-05-29 22:57:01 +0200 (Mon, 29 May 2006) | 3 lines Add News entry for last commit. ........ r46533 | georg.brandl | 2006-05-29 23:04:52 +0200 (Mon, 29 May 2006) | 4 lines Make use of METH_O and METH_NOARGS where possible. Use Py_UnpackTuple instead of PyArg_ParseTuple where possible. ........ r46534 | georg.brandl | 2006-05-29 23:58:42 +0200 (Mon, 29 May 2006) | 3 lines Convert more modules to METH_VARARGS. ........ r46535 | georg.brandl | 2006-05-30 00:00:30 +0200 (Tue, 30 May 2006) | 3 lines Whoops. ........ r46536 | fredrik.lundh | 2006-05-30 00:42:07 +0200 (Tue, 30 May 2006) | 4 lines fixed "abc".count("", 100) == -96 error (hopefully, nobody's relying on the current behaviour ;-) ........ r46537 | bob.ippolito | 2006-05-30 00:55:48 +0200 (Tue, 30 May 2006) | 1 line struct: modulo math plus warning on all endian-explicit formats for compatibility with older struct usage (ugly) ........ r46539 | bob.ippolito | 2006-05-30 02:26:01 +0200 (Tue, 30 May 2006) | 1 line Add a length check to aifc to ensure it doesn't write a bogus file ........ r46540 | tim.peters | 2006-05-30 04:25:25 +0200 (Tue, 30 May 2006) | 10 lines deprecated_err(): Stop bizarre warning messages when the tests are run in the order: test_genexps (or any other doctest-based test) test_struct test_doctest The `warnings` module needs an advertised way to save/restore its internal filter list. ........ r46541 | tim.peters | 2006-05-30 04:26:46 +0200 (Tue, 30 May 2006) | 2 lines Whitespace normalization. ........ r46542 | tim.peters | 2006-05-30 04:30:30 +0200 (Tue, 30 May 2006) | 2 lines Set a binary svn:mime-type property on this UTF-8 encoded file. ........ r46543 | neal.norwitz | 2006-05-30 05:18:50 +0200 (Tue, 30 May 2006) | 1 line Simplify further by using AddStringConstant ........ r46544 | tim.peters | 2006-05-30 06:16:25 +0200 (Tue, 30 May 2006) | 6 lines Convert relevant dict internals to Py_ssize_t. I don't have a box with nearly enough RAM, or an OS, that could get close to tickling this, though (requires a dict w/ at least 2**31 entries). ........ r46545 | neal.norwitz | 2006-05-30 06:19:21 +0200 (Tue, 30 May 2006) | 1 line Remove stray | in comment ........ r46546 | neal.norwitz | 2006-05-30 06:25:05 +0200 (Tue, 30 May 2006) | 1 line Use Py_SAFE_DOWNCAST for safety. Fix format strings. Remove 2 more stray | in comment ........ r46547 | neal.norwitz | 2006-05-30 06:43:23 +0200 (Tue, 30 May 2006) | 1 line No DOWNCAST is required since sizeof(Py_ssize_t) >= sizeof(int) and Py_ReprEntr returns an int ........ r46548 | tim.peters | 2006-05-30 07:04:59 +0200 (Tue, 30 May 2006) | 3 lines dict_print(): Explicitly narrow the return value from a (possibly) wider variable. ........ r46549 | tim.peters | 2006-05-30 07:23:59 +0200 (Tue, 30 May 2006) | 5 lines dict_print(): So that Neal & I don't spend the rest of our lives taking turns rewriting code that works ;-), get rid of casting illusions by declaring a new variable with the obvious type. ........ r46550 | georg.brandl | 2006-05-30 09:04:55 +0200 (Tue, 30 May 2006) | 3 lines Restore exception pickle support. #1497319. ........ r46551 | georg.brandl | 2006-05-30 09:13:29 +0200 (Tue, 30 May 2006) | 3 lines Add a test case for exception pickling. args is never NULL. ........ r46552 | neal.norwitz | 2006-05-30 09:21:10 +0200 (Tue, 30 May 2006) | 1 line Don't fail if the (sub)pkgname already exist. ........ r46553 | georg.brandl | 2006-05-30 09:34:45 +0200 (Tue, 30 May 2006) | 3 lines Disallow keyword args for exceptions. ........ r46554 | neal.norwitz | 2006-05-30 09:36:54 +0200 (Tue, 30 May 2006) | 5 lines I'm impatient. I think this will fix a few more problems with the buildbots. I'm not sure this is the best approach, but I can't think of anything better. If this creates problems, feel free to revert, but I think it's safe and should make things a little better. ........ r46555 | georg.brandl | 2006-05-30 10:17:00 +0200 (Tue, 30 May 2006) | 4 lines Do the check for no keyword arguments in __init__ so that subclasses of Exception can be supplied keyword args ........ r46556 | georg.brandl | 2006-05-30 10:47:19 +0200 (Tue, 30 May 2006) | 3 lines Convert test_exceptions to unittest. ........ r46557 | andrew.kuchling | 2006-05-30 14:52:01 +0200 (Tue, 30 May 2006) | 1 line Add SoC name, and reorganize this section a bit ........ r46559 | tim.peters | 2006-05-30 17:53:34 +0200 (Tue, 30 May 2006) | 11 lines PyLong_FromString(): Continued fraction analysis (explained in a new comment) suggests there are almost certainly large input integers in all non-binary input bases for which one Python digit too few is initally allocated to hold the final result. Instead of assert-failing when that happens, allocate more space. Alas, I estimate it would take a few days to find a specific such case, so this isn't backed up by a new test (not to mention that such a case may take hours to run, since conversion time is quadratic in the number of digits, and preliminary attempts suggested that the smallest such inputs contain at least a million digits). ........ r46560 | fredrik.lundh | 2006-05-30 19:11:48 +0200 (Tue, 30 May 2006) | 3 lines changed find/rfind to return -1 for matches outside the source string ........ r46561 | bob.ippolito | 2006-05-30 19:37:54 +0200 (Tue, 30 May 2006) | 1 line Change wrapping terminology to overflow masking ........ r46562 | fredrik.lundh | 2006-05-30 19:39:58 +0200 (Tue, 30 May 2006) | 3 lines changed count to return 0 for slices outside the source string ........ r46568 | tim.peters | 2006-05-31 01:28:02 +0200 (Wed, 31 May 2006) | 2 lines Whitespace normalization. ........ r46569 | brett.cannon | 2006-05-31 04:19:54 +0200 (Wed, 31 May 2006) | 5 lines Clarify wording on default values for strptime(); defaults are used when better values cannot be inferred. Closes bug #1496315. ........ r46572 | neal.norwitz | 2006-05-31 09:43:27 +0200 (Wed, 31 May 2006) | 1 line Calculate smallest properly (it was off by one) and use proper ssize_t types for Win64 ........ r46573 | neal.norwitz | 2006-05-31 10:01:08 +0200 (Wed, 31 May 2006) | 1 line Revert last checkin, it is better to do make distclean ........ r46574 | neal.norwitz | 2006-05-31 11:02:44 +0200 (Wed, 31 May 2006) | 3 lines On 64-bit platforms running test_struct after test_tarfile would fail since the deprecation warning wouldn't be raised. ........ r46575 | thomas.heller | 2006-05-31 13:37:58 +0200 (Wed, 31 May 2006) | 3 lines PyTuple_Pack is not available in Python 2.3, but ctypes must stay compatible with that. ........ r46576 | andrew.kuchling | 2006-05-31 15:18:56 +0200 (Wed, 31 May 2006) | 1 line 'functional' module was renamed to 'functools' ........ r46577 | kristjan.jonsson | 2006-05-31 15:35:41 +0200 (Wed, 31 May 2006) | 1 line Fixup the PCBuild8 project directory. exceptions.c have moved to Objects, and the functionalmodule.c has been replaced with _functoolsmodule.c. Other minor changes to .vcproj files and .sln to fix compilation ........ r46578 | andrew.kuchling | 2006-05-31 16:08:48 +0200 (Wed, 31 May 2006) | 15 lines [Bug #1473048] SimpleXMLRPCServer and DocXMLRPCServer don't look at the path of the HTTP request at all; you can POST or GET from / or /RPC2 or /blahblahblah with the same results. Security scanners that look for /cgi-bin/phf will therefore report lots of vulnerabilities. Fix: add a .rpc_paths attribute to the SimpleXMLRPCServer class, and report a 404 error if the path isn't on the allowed list. Possibly-controversial aspect of this change: the default makes only '/' and '/RPC2' legal. Maybe this will break people's applications (though I doubt it). We could just set the default to an empty tuple, which would exactly match the current behaviour. ........ r46579 | andrew.kuchling | 2006-05-31 16:12:47 +0200 (Wed, 31 May 2006) | 1 line Mention SimpleXMLRPCServer change ........ r46580 | tim.peters | 2006-05-31 16:28:07 +0200 (Wed, 31 May 2006) | 2 lines Trimmed trailing whitespace. ........ r46581 | tim.peters | 2006-05-31 17:33:22 +0200 (Wed, 31 May 2006) | 4 lines _range_error(): Speed and simplify (there's no real need for loops here). Assert that size_t is actually big enough, and that f->size is at least one. Wrap a long line. ........ r46582 | tim.peters | 2006-05-31 17:34:37 +0200 (Wed, 31 May 2006) | 2 lines Repaired error in new comment. ........ r46584 | neal.norwitz | 2006-06-01 07:32:49 +0200 (Thu, 01 Jun 2006) | 4 lines Remove ; at end of macro. There was a compiler recently that warned about extra semi-colons. It may have been the HP C compiler. This file will trigger a bunch of those warnings now. ........ r46585 | georg.brandl | 2006-06-01 08:39:19 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly unpickle 2.4 exceptions via __setstate__ (patch #1498571) ........ r46586 | georg.brandl | 2006-06-01 10:27:32 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly allocate complex types with tp_alloc. (bug #1498638) ........ r46587 | georg.brandl | 2006-06-01 14:30:46 +0200 (Thu, 01 Jun 2006) | 2 lines Correctly dispatch Faults in loads (patch #1498627) ........ r46588 | georg.brandl | 2006-06-01 15:00:49 +0200 (Thu, 01 Jun 2006) | 3 lines Some code style tweaks, and remove apply. ........ r46589 | armin.rigo | 2006-06-01 15:19:12 +0200 (Thu, 01 Jun 2006) | 5 lines [ 1497053 ] Let dicts propagate the exceptions in user __eq__(). [ 1456209 ] dictresize() vulnerability ( <- backport candidate ). ........ r46590 | tim.peters | 2006-06-01 15:41:46 +0200 (Thu, 01 Jun 2006) | 2 lines Whitespace normalization. ........ r46591 | tim.peters | 2006-06-01 15:49:23 +0200 (Thu, 01 Jun 2006) | 2 lines Record bugs 1275608 and 1456209 as being fixed. ........ r46592 | tim.peters | 2006-06-01 15:56:26 +0200 (Thu, 01 Jun 2006) | 5 lines Re-enable a new empty-string test added during the NFS sprint, but disabled then because str and unicode strings gave different results. The implementations were repaired later during the sprint, but the new test remained disabled. ........ r46594 | tim.peters | 2006-06-01 17:50:44 +0200 (Thu, 01 Jun 2006) | 7 lines Armin committed his patch while I was reviewing it (I'm sure he didn't know this), so merged in some changes I made during review. Nothing material apart from changing a new `mask` local from int to Py_ssize_t. Mostly this is repairing comments that were made incorrect, and adding new comments. Also a few minor code rewrites for clarity or helpful succinctness. ........ r46599 | neal.norwitz | 2006-06-02 06:45:53 +0200 (Fri, 02 Jun 2006) | 1 line Convert docstrings to comments so regrtest -v prints method names ........ r46600 | neal.norwitz | 2006-06-02 06:50:49 +0200 (Fri, 02 Jun 2006) | 2 lines Fix memory leak found by valgrind. ........ r46601 | neal.norwitz | 2006-06-02 06:54:52 +0200 (Fri, 02 Jun 2006) | 1 line More memory leaks from valgrind ........ r46602 | neal.norwitz | 2006-06-02 08:23:00 +0200 (Fri, 02 Jun 2006) | 11 lines Patch #1357836: Prevent an invalid memory read from test_coding in case the done flag is set. In that case, the loop isn't entered. I wonder if rather than setting the done flag in the cases before the loop, if they should just exit early. This code looks like it should be refactored. Backport candidate (also the early break above if decoding_fgets fails) ........ r46603 | martin.blais | 2006-06-02 15:03:43 +0200 (Fri, 02 Jun 2006) | 1 line Fixed struct test to not use unittest. ........ r46605 | tim.peters | 2006-06-03 01:22:51 +0200 (Sat, 03 Jun 2006) | 10 lines pprint functions used to sort a dict (by key) if and only if the output required more than one line. "Small" dicts got displayed in seemingly random order (the hash-induced order produced by dict.__repr__). None of this was documented. Now pprint functions always sort dicts by key, and the docs promise it. This was proposed and agreed to during the PyCon 2006 core sprint -- I just didn't have time for it before now. ........
2006-06-08 11:42:34 -03:00
v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
2001-08-02 01:15:00 -03:00
tp->tp_frees, tp->tp_maxalloc);
if (v == NULL) {
Py_DECREF(result);
return NULL;
}
if (PyList_Append(result, v) < 0) {
Py_DECREF(v);
Py_DECREF(result);
return NULL;
}
Py_DECREF(v);
}
return result;
}
void
2000-07-09 12:48:49 -03:00
inc_count(PyTypeObject *tp)
{
if (tp->tp_next == NULL && tp->tp_prev == NULL) {
1995-04-06 11:46:26 -03:00
/* first time; insert in linked list */
if (tp->tp_next != NULL) /* sanity check */
1997-05-02 00:12:38 -03:00
Py_FatalError("XXX inc_count sanity check");
if (type_list)
type_list->tp_prev = tp;
tp->tp_next = type_list;
/* Note that as of Python 2.2, heap-allocated type objects
* can go away, but this code requires that they stay alive
* until program exit. That's why we're careful with
* refcounts here. type_list gets a new reference to tp,
* while ownership of the reference type_list used to hold
* (if any) was transferred to tp->tp_next in the line above.
* tp is thus effectively immortal after this.
*/
Py_INCREF(tp);
type_list = tp;
#ifdef Py_TRACE_REFS
/* Also insert in the doubly-linked list of all objects,
* if not already there.
*/
_Py_AddToAllObjects((PyObject *)tp, 0);
#endif
}
2001-08-02 01:15:00 -03:00
tp->tp_allocs++;
if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
}
void dec_count(PyTypeObject *tp)
{
tp->tp_frees++;
if (unlist_types_without_objects &&
tp->tp_allocs == tp->tp_frees) {
/* unlink the type from type_list */
if (tp->tp_prev)
tp->tp_prev->tp_next = tp->tp_next;
else
type_list = tp->tp_next;
if (tp->tp_next)
tp->tp_next->tp_prev = tp->tp_prev;
tp->tp_next = tp->tp_prev = NULL;
Py_DECREF(tp);
}
}
#endif
#ifdef Py_REF_DEBUG
/* Log a fatal error; doesn't return. */
void
_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
{
char buf[300];
PyOS_snprintf(buf, sizeof(buf),
"%s:%i object at %p has negative ref count "
"%" PY_FORMAT_SIZE_T "d",
fname, lineno, op, op->ob_refcnt);
Py_FatalError(buf);
}
#endif /* Py_REF_DEBUG */
void
Py_IncRef(PyObject *o)
{
Py_XINCREF(o);
}
void
Py_DecRef(PyObject *o)
{
Py_XDECREF(o);
}
1997-05-02 00:12:38 -03:00
PyObject *
2000-07-09 12:48:49 -03:00
PyObject_Init(PyObject *op, PyTypeObject *tp)
1990-10-14 09:07:46 -03:00
{
if (op == NULL)
return PyErr_NoMemory();
/* Any changes should be reflected in PyObject_INIT (objimpl.h) */
1990-10-14 09:07:46 -03:00
op->ob_type = tp;
1997-05-02 00:12:38 -03:00
_Py_NewReference(op);
1990-10-14 09:07:46 -03:00
return op;
}
PyVarObject *
2006-02-15 13:27:45 -04:00
PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
{
if (op == NULL)
return (PyVarObject *) PyErr_NoMemory();
/* Any changes should be reflected in PyObject_INIT_VAR */
op->ob_size = size;
op->ob_type = tp;
_Py_NewReference((PyObject *)op);
return op;
}
PyObject *
2000-07-09 12:48:49 -03:00
_PyObject_New(PyTypeObject *tp)
{
PyObject *op;
op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
if (op == NULL)
return PyErr_NoMemory();
return PyObject_INIT(op, tp);
}
PyVarObject *
2006-02-15 13:27:45 -04:00
_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
1990-10-14 09:07:46 -03:00
{
PyVarObject *op;
const size_t size = _PyObject_VAR_SIZE(tp, nitems);
op = (PyVarObject *) PyObject_MALLOC(size);
1990-10-14 09:07:46 -03:00
if (op == NULL)
return (PyVarObject *)PyErr_NoMemory();
return PyObject_INIT_VAR(op, tp, nitems);
}
/* for binary compatibility with 2.2 */
#undef _PyObject_Del
void
2000-07-09 12:48:49 -03:00
_PyObject_Del(PyObject *op)
{
2000-06-30 22:00:38 -03:00
PyObject_FREE(op);
1990-10-14 09:07:46 -03:00
}
/* Implementation of PyObject_Print with recursion checking */
static int
internal_print(PyObject *op, FILE *fp, int flags, int nesting)
1990-10-14 09:07:46 -03:00
{
int ret = 0;
if (nesting > 10) {
PyErr_SetString(PyExc_RuntimeError, "print recursion");
return -1;
}
1997-05-02 00:12:38 -03:00
if (PyErr_CheckSignals())
1991-06-07 13:10:43 -03:00
return -1;
#ifdef USE_STACKCHECK
if (PyOS_CheckStack()) {
PyErr_SetString(PyExc_MemoryError, "stack overflow");
return -1;
}
#endif
clearerr(fp); /* Clear any previous error condition */
1991-06-07 13:10:43 -03:00
if (op == NULL) {
fprintf(fp, "<nil>");
1990-10-14 09:07:46 -03:00
}
1991-06-07 13:10:43 -03:00
else {
if (op->ob_refcnt <= 0)
/* XXX(twouters) cast refcount to long until %zd is
universally available */
fprintf(fp, "<refcnt %ld at %p>",
(long)op->ob_refcnt, op);
else if (op->ob_type->tp_print == NULL) {
PyObject *s;
if (flags & Py_PRINT_RAW)
s = PyObject_Str(op);
else
s = PyObject_Repr(op);
if (s == NULL)
ret = -1;
else {
ret = internal_print(s, fp, Py_PRINT_RAW,
nesting+1);
}
Py_XDECREF(s);
}
1991-06-07 13:10:43 -03:00
else
ret = (*op->ob_type->tp_print)(op, fp, flags);
1991-06-07 13:10:43 -03:00
}
if (ret == 0) {
if (ferror(fp)) {
1997-05-02 00:12:38 -03:00
PyErr_SetFromErrno(PyExc_IOError);
clearerr(fp);
ret = -1;
}
}
return ret;
1990-10-14 09:07:46 -03:00
}
int
PyObject_Print(PyObject *op, FILE *fp, int flags)
{
return internal_print(op, fp, flags, 0);
}
/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
void _PyObject_Dump(PyObject* op)
{
if (op == NULL)
fprintf(stderr, "NULL\n");
else {
fprintf(stderr, "object : ");
(void)PyObject_Print(op, stderr, 0);
/* XXX(twouters) cast refcount to long until %zd is
universally available */
fprintf(stderr, "\n"
"type : %s\n"
"refcount: %ld\n"
"address : %p\n",
op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,
(long)op->ob_refcnt,
op);
}
}
1997-05-02 00:12:38 -03:00
PyObject *
2000-07-09 12:48:49 -03:00
PyObject_Repr(PyObject *v)
1990-10-14 09:07:46 -03:00
{
1997-05-02 00:12:38 -03:00
if (PyErr_CheckSignals())
1991-06-07 13:10:43 -03:00
return NULL;
#ifdef USE_STACKCHECK
if (PyOS_CheckStack()) {
PyErr_SetString(PyExc_MemoryError, "stack overflow");
return NULL;
}
#endif
1991-06-07 13:10:43 -03:00
if (v == NULL)
1997-05-02 00:12:38 -03:00
return PyString_FromString("<NULL>");
else if (v->ob_type->tp_repr == NULL)
return PyString_FromFormat("<%s object at %p>",
v->ob_type->tp_name, v);
else {
PyObject *res;
res = (*v->ob_type->tp_repr)(v);
if (res == NULL)
return NULL;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(res)) {
PyObject* str;
str = PyUnicode_AsEncodedString(res, NULL, NULL);
Py_DECREF(res);
if (str)
res = str;
else
return NULL;
}
#endif
if (!PyString_Check(res)) {
PyErr_Format(PyExc_TypeError,
"__repr__ returned non-string (type %.200s)",
res->ob_type->tp_name);
Py_DECREF(res);
return NULL;
}
return res;
}
1990-10-14 09:07:46 -03:00
}
1997-05-02 00:12:38 -03:00
PyObject *
_PyObject_Str(PyObject *v)
{
PyObject *res;
int type_ok;
if (v == NULL)
1997-05-02 00:12:38 -03:00
return PyString_FromString("<NULL>");
if (PyString_CheckExact(v)) {
1997-05-02 00:12:38 -03:00
Py_INCREF(v);
return v;
}
#ifdef Py_USING_UNICODE
if (PyUnicode_CheckExact(v)) {
Py_INCREF(v);
return v;
}
#endif
if (v->ob_type->tp_str == NULL)
return PyObject_Repr(v);
res = (*v->ob_type->tp_str)(v);
if (res == NULL)
return NULL;
type_ok = PyString_Check(res);
#ifdef Py_USING_UNICODE
type_ok = type_ok || PyUnicode_Check(res);
#endif
if (!type_ok) {
PyErr_Format(PyExc_TypeError,
"__str__ returned non-string (type %.200s)",
res->ob_type->tp_name);
Py_DECREF(res);
return NULL;
}
return res;
}
PyObject *
PyObject_Str(PyObject *v)
{
PyObject *res = _PyObject_Str(v);
if (res == NULL)
return NULL;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(res)) {
PyObject* str;
str = PyUnicode_AsEncodedString(res, NULL, NULL);
Py_DECREF(res);
if (str)
res = str;
else
return NULL;
}
#endif
assert(PyString_Check(res));
return res;
}
#ifdef Py_USING_UNICODE
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
PyObject *
PyObject_Unicode(PyObject *v)
{
PyObject *res;
PyObject *func;
PyObject *str;
static PyObject *unicodestr;
if (v == NULL) {
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
res = PyString_FromString("<NULL>");
if (res == NULL)
return NULL;
str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Py_DECREF(res);
return str;
} else if (PyUnicode_CheckExact(v)) {
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
Py_INCREF(v);
return v;
}
/* XXX As soon as we have a tp_unicode slot, we should
check this before trying the __unicode__
method. */
if (unicodestr == NULL) {
unicodestr= PyString_InternFromString("__unicode__");
if (unicodestr == NULL)
return NULL;
}
func = PyObject_GetAttr(v, unicodestr);
if (func != NULL) {
res = PyEval_CallObject(func, (PyObject *)NULL);
Py_DECREF(func);
SF patch #470578: Fixes to synchronize unicode() and str() This patch implements what we have discussed on python-dev late in September: str(obj) and unicode(obj) should behave similar, while the old behaviour is retained for unicode(obj, encoding, errors). The patch also adds a new feature with which objects can provide unicode(obj) with input data: the __unicode__ method. Currently no new tp_unicode slot is implemented; this is left as option for the future. Note that PyUnicode_FromEncodedObject() no longer accepts Unicode objects as input. The API name already suggests that Unicode objects do not belong in the list of acceptable objects and the functionality was only needed because PyUnicode_FromEncodedObject() was being used directly by unicode(). The latter was changed in the discussed way: * unicode(obj) calls PyObject_Unicode() * unicode(obj, encoding, errors) calls PyUnicode_FromEncodedObject() One thing left open to discussion is whether to leave the PyUnicode_FromObject() API as a thin API extension on top of PyUnicode_FromEncodedObject() or to turn it into a (macro) alias for PyObject_Unicode() and deprecate it. Doing so would have some surprising consequences though, e.g. u"abc" + 123 would turn out as u"abc123"... [Marc-Andre didn't have time to check this in before the deadline. I hope this is OK, Marc-Andre! You can still make changes and commit them on the trunk after the branch has been made, but then please mail Barry a context diff if you want the change to be merged into the 2.2b1 release branch. GvR]
2001-10-18 23:01:31 -03:00
}
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
else {
PyErr_Clear();
if (PyUnicode_Check(v)) {
/* For a Unicode subtype that's didn't overwrite __unicode__,
return a true Unicode object with the same data. */
return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
PyUnicode_GET_SIZE(v));
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
}
if (PyString_CheckExact(v)) {
Py_INCREF(v);
res = v;
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
}
SF patch #470578: Fixes to synchronize unicode() and str() This patch implements what we have discussed on python-dev late in September: str(obj) and unicode(obj) should behave similar, while the old behaviour is retained for unicode(obj, encoding, errors). The patch also adds a new feature with which objects can provide unicode(obj) with input data: the __unicode__ method. Currently no new tp_unicode slot is implemented; this is left as option for the future. Note that PyUnicode_FromEncodedObject() no longer accepts Unicode objects as input. The API name already suggests that Unicode objects do not belong in the list of acceptable objects and the functionality was only needed because PyUnicode_FromEncodedObject() was being used directly by unicode(). The latter was changed in the discussed way: * unicode(obj) calls PyObject_Unicode() * unicode(obj, encoding, errors) calls PyUnicode_FromEncodedObject() One thing left open to discussion is whether to leave the PyUnicode_FromObject() API as a thin API extension on top of PyUnicode_FromEncodedObject() or to turn it into a (macro) alias for PyObject_Unicode() and deprecate it. Doing so would have some surprising consequences though, e.g. u"abc" + 123 would turn out as u"abc123"... [Marc-Andre didn't have time to check this in before the deadline. I hope this is OK, Marc-Andre! You can still make changes and commit them on the trunk after the branch has been made, but then please mail Barry a context diff if you want the change to be merged into the 2.2b1 release branch. GvR]
2001-10-18 23:01:31 -03:00
else {
if (v->ob_type->tp_str != NULL)
res = (*v->ob_type->tp_str)(v);
else
res = PyObject_Repr(v);
}
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
}
if (res == NULL)
return NULL;
if (!PyUnicode_Check(res)) {
SF patch #470578: Fixes to synchronize unicode() and str() This patch implements what we have discussed on python-dev late in September: str(obj) and unicode(obj) should behave similar, while the old behaviour is retained for unicode(obj, encoding, errors). The patch also adds a new feature with which objects can provide unicode(obj) with input data: the __unicode__ method. Currently no new tp_unicode slot is implemented; this is left as option for the future. Note that PyUnicode_FromEncodedObject() no longer accepts Unicode objects as input. The API name already suggests that Unicode objects do not belong in the list of acceptable objects and the functionality was only needed because PyUnicode_FromEncodedObject() was being used directly by unicode(). The latter was changed in the discussed way: * unicode(obj) calls PyObject_Unicode() * unicode(obj, encoding, errors) calls PyUnicode_FromEncodedObject() One thing left open to discussion is whether to leave the PyUnicode_FromObject() API as a thin API extension on top of PyUnicode_FromEncodedObject() or to turn it into a (macro) alias for PyObject_Unicode() and deprecate it. Doing so would have some surprising consequences though, e.g. u"abc" + 123 would turn out as u"abc123"... [Marc-Andre didn't have time to check this in before the deadline. I hope this is OK, Marc-Andre! You can still make changes and commit them on the trunk after the branch has been made, but then please mail Barry a context diff if you want the change to be merged into the 2.2b1 release branch. GvR]
2001-10-18 23:01:31 -03:00
str = PyUnicode_FromEncodedObject(res, NULL, "strict");
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
Py_DECREF(res);
res = str;
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
}
return res;
}
#endif
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
2001-01-18 18:07:06 -04:00
/* Helper to warn about deprecated tp_compare return values. Return:
-2 for an exception;
-1 if v < w;
0 if v == w;
1 if v > w.
(This function cannot return 2.)
*/
static int
adjust_tp_compare(int c)
{
if (PyErr_Occurred()) {
if (c != -1 && c != -2) {
PyObject *t, *v, *tb;
PyErr_Fetch(&t, &v, &tb);
if (PyErr_Warn(PyExc_RuntimeWarning,
"tp_compare didn't return -1 or -2 "
"for exception") < 0) {
Py_XDECREF(t);
Py_XDECREF(v);
Py_XDECREF(tb);
}
else
PyErr_Restore(t, v, tb);
}
return -2;
}
else if (c < -1 || c > 1) {
if (PyErr_Warn(PyExc_RuntimeWarning,
"tp_compare didn't return -1, 0 or 1") < 0)
return -2;
else
return c < -1 ? -1 : 1;
}
else {
assert(c >= -1 && c <= 1);
return c;
}
}
/* Macro to get the tp_richcompare field of a type if defined */
#define RICHCOMPARE(t) ((t)->tp_richcompare)
/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
/* Try a genuine rich comparison, returning an object. Return:
NULL for exception;
NotImplemented if this particular rich comparison is not implemented or
undefined;
some object not equal to NotImplemented if it is implemented
(this latter object may not be a Boolean).
*/
static PyObject *
try_rich_compare(PyObject *v, PyObject *w, int op)
{
richcmpfunc f;
PyObject *res;
if (v->ob_type != w->ob_type &&
PyType_IsSubtype(w->ob_type, v->ob_type) &&
(f = RICHCOMPARE(w->ob_type)) != NULL) {
res = (*f)(w, v, _Py_SwappedOp[op]);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
}
if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
res = (*f)(v, w, op);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
}
if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
return (*f)(w, v, _Py_SwappedOp[op]);
}
res = Py_NotImplemented;
Py_INCREF(res);
return res;
}
/* Try a genuine rich comparison, returning an int. Return:
-1 for exception (including the case where try_rich_compare() returns an
object that's not a Boolean);
0 if the outcome is false;
1 if the outcome is true;
2 if this particular rich comparison is not implemented or undefined.
*/
static int
try_rich_compare_bool(PyObject *v, PyObject *w, int op)
{
PyObject *res;
int ok;
if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
return 2; /* Shortcut, avoid INCREF+DECREF */
res = try_rich_compare(v, w, op);
if (res == NULL)
return -1;
if (res == Py_NotImplemented) {
Py_DECREF(res);
return 2;
}
ok = PyObject_IsTrue(res);
Py_DECREF(res);
return ok;
}
/* Try rich comparisons to determine a 3-way comparison. Return:
-2 for an exception;
-1 if v < w;
0 if v == w;
1 if v > w;
2 if this particular rich comparison is not implemented or undefined.
*/
static int
try_rich_to_3way_compare(PyObject *v, PyObject *w)
{
static struct { int op; int outcome; } tries[3] = {
/* Try this operator, and if it is true, use this outcome: */
{Py_EQ, 0},
{Py_LT, -1},
{Py_GT, 1},
};
int i;
if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
return 2; /* Shortcut */
for (i = 0; i < 3; i++) {
switch (try_rich_compare_bool(v, w, tries[i].op)) {
case -1:
return -2;
case 1:
return tries[i].outcome;
}
}
return 2;
}
/* Try a 3-way comparison, returning an int. Return:
-2 for an exception;
-1 if v < w;
0 if v == w;
1 if v > w;
2 if this particular 3-way comparison is not implemented or undefined.
*/
static int
try_3way_compare(PyObject *v, PyObject *w)
{
int c;
cmpfunc f;
/* Comparisons involving instances are given to instance_compare,
which has the same return conventions as this function. */
f = v->ob_type->tp_compare;
if (PyInstance_Check(v))
return (*f)(v, w);
if (PyInstance_Check(w))
return (*w->ob_type->tp_compare)(v, w);
/* If both have the same (non-NULL) tp_compare, use it. */
if (f != NULL && f == w->ob_type->tp_compare) {
c = (*f)(v, w);
return adjust_tp_compare(c);
}
/* If either tp_compare is _PyObject_SlotCompare, that's safe. */
if (f == _PyObject_SlotCompare ||
w->ob_type->tp_compare == _PyObject_SlotCompare)
return _PyObject_SlotCompare(v, w);
/* If we're here, v and w,
a) are not instances;
b) have different types or a type without tp_compare; and
c) don't have a user-defined tp_compare.
tp_compare implementations in C assume that both arguments
have their type, so we give up if the coercion fails or if
it yields types which are still incompatible (which can
happen with a user-defined nb_coerce).
*/
c = PyNumber_CoerceEx(&v, &w);
if (c < 0)
return -2;
if (c > 0)
return 2;
f = v->ob_type->tp_compare;
if (f != NULL && f == w->ob_type->tp_compare) {
c = (*f)(v, w);
Py_DECREF(v);
Py_DECREF(w);
return adjust_tp_compare(c);
}
/* No comparison defined */
Py_DECREF(v);
Py_DECREF(w);
return 2;
}
/* Final fallback 3-way comparison, returning an int. Return:
-2 if an error occurred;
-1 if v < w;
0 if v == w;
1 if v > w.
*/
static int
default_3way_compare(PyObject *v, PyObject *w)
{
int c;
const char *vname, *wname;
if (v->ob_type == w->ob_type) {
/* When comparing these pointers, they must be cast to
* integer types (i.e. Py_uintptr_t, our spelling of C9X's
* uintptr_t). ANSI specifies that pointer compares other
* than == and != to non-related structures are undefined.
*/
Py_uintptr_t vv = (Py_uintptr_t)v;
Py_uintptr_t ww = (Py_uintptr_t)w;
return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
}
#ifdef Py_USING_UNICODE
/* Special case for Unicode */
if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
c = PyUnicode_Compare(v, w);
if (!PyErr_Occurred())
return c;
/* TypeErrors are ignored: if Unicode coercion fails due
to one of the arguments not having the right type, we
continue as defined by the coercion protocol (see
above). Luckily, decoding errors are reported as
ValueErrors and are not masked by this technique. */
if (!PyErr_ExceptionMatches(PyExc_TypeError))
return -2;
PyErr_Clear();
}
#endif
/* None is smaller than anything */
if (v == Py_None)
return -1;
if (w == Py_None)
return 1;
/* different type: compare type names; numbers are smaller */
if (PyNumber_Check(v))
vname = "";
else
vname = v->ob_type->tp_name;
if (PyNumber_Check(w))
wname = "";
else
wname = w->ob_type->tp_name;
c = strcmp(vname, wname);
if (c < 0)
return -1;
if (c > 0)
return 1;
/* Same type name, or (more likely) incomparable numeric types */
return ((Py_uintptr_t)(v->ob_type) < (
Py_uintptr_t)(w->ob_type)) ? -1 : 1;
}
/* Do a 3-way comparison, by hook or by crook. Return:
-2 for an exception (but see below);
-1 if v < w;
0 if v == w;
1 if v > w;
BUT: if the object implements a tp_compare function, it returns
whatever this function returns (whether with an exception or not).
*/
static int
do_cmp(PyObject *v, PyObject *w)
{
int c;
cmpfunc f;
if (v->ob_type == w->ob_type
&& (f = v->ob_type->tp_compare) != NULL) {
c = (*f)(v, w);
if (PyInstance_Check(v)) {
/* Instance tp_compare has a different signature.
But if it returns undefined we fall through. */
if (c != 2)
return c;
2002-05-31 17:23:33 -03:00
/* Else fall through to try_rich_to_3way_compare() */
}
else
return adjust_tp_compare(c);
}
/* We only get here if one of the following is true:
a) v and w have different types
b) v and w have the same type, which doesn't have tp_compare
c) v and w are instances, and either __cmp__ is not defined or
__cmp__ returns NotImplemented
*/
c = try_rich_to_3way_compare(v, w);
if (c < 2)
return c;
c = try_3way_compare(v, w);
if (c < 2)
return c;
return default_3way_compare(v, w);
}
/* Compare v to w. Return
-1 if v < w or exception (PyErr_Occurred() true in latter case).
0 if v == w.
1 if v > w.
XXX The docs (C API manual) say the return value is undefined in case
XXX of error.
*/
1990-10-14 09:07:46 -03:00
int
2000-07-09 12:48:49 -03:00
PyObject_Compare(PyObject *v, PyObject *w)
1990-10-14 09:07:46 -03:00
{
int result;
if (v == NULL || w == NULL) {
PyErr_BadInternalCall();
return -1;
}
1990-10-14 09:07:46 -03:00
if (v == w)
return 0;
if (Py_EnterRecursiveCall(" in cmp"))
return -1;
result = do_cmp(v, w);
Py_LeaveRecursiveCall();
return result < 0 ? -1 : result;
}
/* Return (new reference to) Py_True or Py_False. */
static PyObject *
convert_3way_to_object(int op, int c)
{
PyObject *result;
switch (op) {
case Py_LT: c = c < 0; break;
case Py_LE: c = c <= 0; break;
case Py_EQ: c = c == 0; break;
case Py_NE: c = c != 0; break;
case Py_GT: c = c > 0; break;
case Py_GE: c = c >= 0; break;
}
result = c ? Py_True : Py_False;
Py_INCREF(result);
return result;
1990-10-14 09:07:46 -03:00
}
/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
Return
NULL if error
Py_True if v op w
Py_False if not (v op w)
*/
static PyObject *
try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
{
int c;
c = try_3way_compare(v, w);
if (c >= 2)
c = default_3way_compare(v, w);
if (c <= -2)
return NULL;
return convert_3way_to_object(op, c);
}
1990-10-14 09:07:46 -03:00
/* Do rich comparison on v and w. Return
NULL if error
Else a new reference to an object other than Py_NotImplemented, usually(?):
Py_True if v op w
Py_False if not (v op w)
*/
2001-01-21 12:25:18 -04:00
static PyObject *
do_richcmp(PyObject *v, PyObject *w, int op)
{
PyObject *res;
res = try_rich_compare(v, w, op);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
return try_3way_to_rich_compare(v, w, op);
}
/* Return:
NULL for exception;
some object not equal to NotImplemented if it is implemented
(this latter object may not be a Boolean).
*/
PyObject *
PyObject_RichCompare(PyObject *v, PyObject *w, int op)
{
PyObject *res;
assert(Py_LT <= op && op <= Py_GE);
if (Py_EnterRecursiveCall(" in cmp"))
return NULL;
/* If the types are equal, and not old-style instances, try to
get out cheap (don't bother with coercions etc.). */
if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
cmpfunc fcmp;
richcmpfunc frich = RICHCOMPARE(v->ob_type);
/* If the type has richcmp, try it first. try_rich_compare
tries it two-sided, which is not needed since we've a
single type only. */
if (frich != NULL) {
res = (*frich)(v, w, op);
if (res != Py_NotImplemented)
goto Done;
Py_DECREF(res);
}
/* No richcmp, or this particular richmp not implemented.
Try 3-way cmp. */
fcmp = v->ob_type->tp_compare;
if (fcmp != NULL) {
int c = (*fcmp)(v, w);
c = adjust_tp_compare(c);
if (c == -2) {
res = NULL;
goto Done;
}
res = convert_3way_to_object(op, c);
goto Done;
}
}
/* Fast path not taken, or couldn't deliver a useful result. */
res = do_richcmp(v, w, op);
Done:
Py_LeaveRecursiveCall();
return res;
}
/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
int
PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
{
PyObject *res;
int ok;
/* Quick result when objects are the same.
Guarantees that identity implies equality. */
if (v == w) {
if (op == Py_EQ)
return 1;
else if (op == Py_NE)
return 0;
}
res = PyObject_RichCompare(v, w, op);
if (res == NULL)
return -1;
if (PyBool_Check(res))
ok = (res == Py_True);
else
ok = PyObject_IsTrue(res);
Py_DECREF(res);
return ok;
}
/* Set of hash utility functions to help maintaining the invariant that
2004-03-21 13:35:06 -04:00
if a==b then hash(a)==hash(b)
All the utility functions (_Py_Hash*()) return "-1" to signify an error.
*/
long
2000-07-09 12:48:49 -03:00
_Py_HashDouble(double v)
{
double intpart, fractpart;
int expo;
long hipart;
long x; /* the final hash value */
/* This is designed so that Python numbers of different types
* that compare equal hash to the same value; otherwise comparisons
* of mapping keys will turn out weird.
*/
fractpart = modf(v, &intpart);
if (fractpart == 0.0) {
/* This must return the same hash as an equal int or long. */
if (intpart > LONG_MAX || -intpart > LONG_MAX) {
/* Convert to long and use its hash. */
PyObject *plong; /* converted to Python long */
if (Py_IS_INFINITY(intpart))
/* can't convert to long int -- arbitrary */
v = v < 0 ? -271828.0 : 314159.0;
plong = PyLong_FromDouble(v);
if (plong == NULL)
return -1;
x = PyObject_Hash(plong);
Py_DECREF(plong);
return x;
}
/* Fits in a C long == a Python int, so is its own hash. */
x = (long)intpart;
if (x == -1)
x = -2;
return x;
}
/* The fractional part is non-zero, so we don't have to worry about
* making this match the hash of some other type.
* Use frexp to get at the bits in the double.
* Since the VAX D double format has 56 mantissa bits, which is the
* most of any double format in use, each of these parts may have as
* many as (but no more than) 56 significant bits.
* So, assuming sizeof(long) >= 4, each part can be broken into two
* longs; frexp and multiplication are used to do that.
* Also, since the Cray double format has 15 exponent bits, which is
* the most of any double format in use, shifting the exponent field
* left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
*/
v = frexp(v, &expo);
v *= 2147483648.0; /* 2**31 */
hipart = (long)v; /* take the top 32 bits */
v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
x = hipart + (long)v + (expo << 15);
if (x == -1)
x = -2;
return x;
}
long
2000-07-09 12:48:49 -03:00
_Py_HashPointer(void *p)
{
#if SIZEOF_LONG >= SIZEOF_VOID_P
return (long)p;
#else
/* convert to a Python long and hash that */
PyObject* longobj;
long x;
if ((longobj = PyLong_FromVoidPtr(p)) == NULL) {
x = -1;
goto finally;
}
x = PyObject_Hash(longobj);
finally:
Py_XDECREF(longobj);
return x;
#endif
}
long
2000-07-09 12:48:49 -03:00
PyObject_Hash(PyObject *v)
{
1997-05-02 00:12:38 -03:00
PyTypeObject *tp = v->ob_type;
if (tp->tp_hash != NULL)
return (*tp->tp_hash)(v);
if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
return _Py_HashPointer(v); /* Use address as hash value */
}
/* If there's a cmp but no hash defined, the object can't be hashed */
1997-05-02 00:12:38 -03:00
PyErr_SetString(PyExc_TypeError, "unhashable type");
return -1;
}
1997-05-02 00:12:38 -03:00
PyObject *
PyObject_GetAttrString(PyObject *v, const char *name)
1990-12-20 11:06:42 -04:00
{
2001-08-02 01:15:00 -03:00
PyObject *w, *res;
2001-08-02 01:15:00 -03:00
if (v->ob_type->tp_getattr != NULL)
return (*v->ob_type->tp_getattr)(v, (char*)name);
2001-08-02 01:15:00 -03:00
w = PyString_InternFromString(name);
if (w == NULL)
return NULL;
res = PyObject_GetAttr(v, w);
Py_XDECREF(w);
return res;
1990-12-20 11:06:42 -04:00
}
int
PyObject_HasAttrString(PyObject *v, const char *name)
{
1997-05-02 00:12:38 -03:00
PyObject *res = PyObject_GetAttrString(v, name);
if (res != NULL) {
1997-05-02 00:12:38 -03:00
Py_DECREF(res);
return 1;
}
1997-05-02 00:12:38 -03:00
PyErr_Clear();
return 0;
}
1990-12-20 11:06:42 -04:00
int
PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
1990-12-20 11:06:42 -04:00
{
2001-08-02 01:15:00 -03:00
PyObject *s;
int res;
2001-08-02 01:15:00 -03:00
if (v->ob_type->tp_setattr != NULL)
return (*v->ob_type->tp_setattr)(v, (char*)name, w);
2001-08-02 01:15:00 -03:00
s = PyString_InternFromString(name);
if (s == NULL)
return -1;
res = PyObject_SetAttr(v, s, w);
Py_XDECREF(s);
return res;
}
PyObject *
2000-07-09 12:48:49 -03:00
PyObject_GetAttr(PyObject *v, PyObject *name)
{
2001-08-02 01:15:00 -03:00
PyTypeObject *tp = v->ob_type;
if (!PyString_Check(name)) {
#ifdef Py_USING_UNICODE
/* The Unicode to string conversion is done here because the
existing tp_getattro slots expect a string object as name
and we wouldn't want to break those. */
if (PyUnicode_Check(name)) {
name = _PyUnicode_AsDefaultEncodedString(name, NULL);
if (name == NULL)
return NULL;
}
else
#endif
{
PyErr_SetString(PyExc_TypeError,
"attribute name must be string");
return NULL;
}
}
2001-08-02 01:15:00 -03:00
if (tp->tp_getattro != NULL)
return (*tp->tp_getattro)(v, name);
if (tp->tp_getattr != NULL)
return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
PyErr_Format(PyExc_AttributeError,
"'%.50s' object has no attribute '%.400s'",
tp->tp_name, PyString_AS_STRING(name));
return NULL;
}
int
2000-07-09 12:48:49 -03:00
PyObject_HasAttr(PyObject *v, PyObject *name)
{
PyObject *res = PyObject_GetAttr(v, name);
if (res != NULL) {
Py_DECREF(res);
return 1;
}
PyErr_Clear();
return 0;
}
int
2000-07-09 12:48:49 -03:00
PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
{
2001-08-02 01:15:00 -03:00
PyTypeObject *tp = v->ob_type;
int err;
if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
/* The Unicode to string conversion is done here because the
existing tp_setattro slots expect a string object as name
and we wouldn't want to break those. */
if (PyUnicode_Check(name)) {
name = PyUnicode_AsEncodedString(name, NULL, NULL);
if (name == NULL)
return -1;
}
else
#endif
{
PyErr_SetString(PyExc_TypeError,
"attribute name must be string");
return -1;
}
}
2001-08-02 01:15:00 -03:00
else
Py_INCREF(name);
PyString_InternInPlace(&name);
if (tp->tp_setattro != NULL) {
err = (*tp->tp_setattro)(v, name, value);
Py_DECREF(name);
return err;
}
if (tp->tp_setattr != NULL) {
err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
Py_DECREF(name);
return err;
}
Py_DECREF(name);
2001-08-02 01:15:00 -03:00
if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
PyErr_Format(PyExc_TypeError,
"'%.100s' object has no attributes "
"(%s .%.100s)",
tp->tp_name,
value==NULL ? "del" : "assign to",
PyString_AS_STRING(name));
else
PyErr_Format(PyExc_TypeError,
"'%.100s' object has only read-only attributes "
"(%s .%.100s)",
tp->tp_name,
value==NULL ? "del" : "assign to",
PyString_AS_STRING(name));
return -1;
}
/* Helper to get a pointer to an object's __dict__ slot, if any */
PyObject **
_PyObject_GetDictPtr(PyObject *obj)
{
Py_ssize_t dictoffset;
2001-08-02 01:15:00 -03:00
PyTypeObject *tp = obj->ob_type;
dictoffset = tp->tp_dictoffset;
if (dictoffset == 0)
return NULL;
if (dictoffset < 0) {
2006-02-15 13:27:45 -04:00
Py_ssize_t tsize;
size_t size;
tsize = ((PyVarObject *)obj)->ob_size;
if (tsize < 0)
tsize = -tsize;
size = _PyObject_VAR_SIZE(tp, tsize);
dictoffset += (long)size;
assert(dictoffset > 0);
assert(dictoffset % SIZEOF_VOID_P == 0);
2001-08-02 01:15:00 -03:00
}
return (PyObject **) ((char *)obj + dictoffset);
}
PyObject *
PyObject_SelfIter(PyObject *obj)
{
Py_INCREF(obj);
return obj;
}
/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
2001-08-02 01:15:00 -03:00
PyObject *
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
{
PyTypeObject *tp = obj->ob_type;
PyObject *descr = NULL;
PyObject *res = NULL;
2001-08-02 01:15:00 -03:00
descrgetfunc f;
Py_ssize_t dictoffset;
2001-08-02 01:15:00 -03:00
PyObject **dictptr;
if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
/* The Unicode to string conversion is done here because the
existing tp_setattro slots expect a string object as name
and we wouldn't want to break those. */
if (PyUnicode_Check(name)) {
name = PyUnicode_AsEncodedString(name, NULL, NULL);
if (name == NULL)
return NULL;
}
else
#endif
{
PyErr_SetString(PyExc_TypeError,
"attribute name must be string");
return NULL;
}
}
else
Py_INCREF(name);
2001-08-02 01:15:00 -03:00
if (tp->tp_dict == NULL) {
if (PyType_Ready(tp) < 0)
goto done;
2001-08-02 01:15:00 -03:00
}
/* Inline _PyType_Lookup */
{
2006-02-15 13:27:45 -04:00
Py_ssize_t i, n;
PyObject *mro, *base, *dict;
/* Look in tp_dict of types in MRO */
mro = tp->tp_mro;
assert(mro != NULL);
assert(PyTuple_Check(mro));
n = PyTuple_GET_SIZE(mro);
for (i = 0; i < n; i++) {
base = PyTuple_GET_ITEM(mro, i);
if (PyClass_Check(base))
dict = ((PyClassObject *)base)->cl_dict;
else {
assert(PyType_Check(base));
dict = ((PyTypeObject *)base)->tp_dict;
}
assert(dict && PyDict_Check(dict));
descr = PyDict_GetItem(dict, name);
if (descr != NULL)
break;
}
}
Py_XINCREF(descr);
2001-08-02 01:15:00 -03:00
f = NULL;
if (descr != NULL) {
2001-08-02 01:15:00 -03:00
f = descr->ob_type->tp_descr_get;
if (f != NULL && PyDescr_IsData(descr)) {
res = f(descr, obj, (PyObject *)obj->ob_type);
Py_DECREF(descr);
goto done;
}
2001-08-02 01:15:00 -03:00
}
/* Inline _PyObject_GetDictPtr */
dictoffset = tp->tp_dictoffset;
if (dictoffset != 0) {
PyObject *dict;
if (dictoffset < 0) {
2006-02-15 13:27:45 -04:00
Py_ssize_t tsize;
size_t size;
tsize = ((PyVarObject *)obj)->ob_size;
if (tsize < 0)
tsize = -tsize;
size = _PyObject_VAR_SIZE(tp, tsize);
dictoffset += (long)size;
assert(dictoffset > 0);
assert(dictoffset % SIZEOF_VOID_P == 0);
}
dictptr = (PyObject **) ((char *)obj + dictoffset);
dict = *dictptr;
2001-08-02 01:15:00 -03:00
if (dict != NULL) {
res = PyDict_GetItem(dict, name);
2001-08-02 01:15:00 -03:00
if (res != NULL) {
Py_INCREF(res);
Py_XDECREF(descr);
goto done;
2001-08-02 01:15:00 -03:00
}
}
}
if (f != NULL) {
res = f(descr, obj, (PyObject *)obj->ob_type);
Py_DECREF(descr);
goto done;
}
2001-08-02 01:15:00 -03:00
if (descr != NULL) {
res = descr;
/* descr was already increfed above */
goto done;
2001-08-02 01:15:00 -03:00
}
PyErr_Format(PyExc_AttributeError,
"'%.50s' object has no attribute '%.400s'",
tp->tp_name, PyString_AS_STRING(name));
done:
Py_DECREF(name);
return res;
2001-08-02 01:15:00 -03:00
}
int
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
{
PyTypeObject *tp = obj->ob_type;
PyObject *descr;
descrsetfunc f;
PyObject **dictptr;
int res = -1;
if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
/* The Unicode to string conversion is done here because the
existing tp_setattro slots expect a string object as name
and we wouldn't want to break those. */
if (PyUnicode_Check(name)) {
name = PyUnicode_AsEncodedString(name, NULL, NULL);
if (name == NULL)
return -1;
}
else
#endif
{
PyErr_SetString(PyExc_TypeError,
"attribute name must be string");
return -1;
}
}
else
Py_INCREF(name);
2001-08-02 01:15:00 -03:00
if (tp->tp_dict == NULL) {
if (PyType_Ready(tp) < 0)
goto done;
2001-08-02 01:15:00 -03:00
}
descr = _PyType_Lookup(tp, name);
f = NULL;
if (descr != NULL) {
2001-08-02 01:15:00 -03:00
f = descr->ob_type->tp_descr_set;
if (f != NULL && PyDescr_IsData(descr)) {
res = f(descr, obj, value);
goto done;
}
2001-08-02 01:15:00 -03:00
}
dictptr = _PyObject_GetDictPtr(obj);
if (dictptr != NULL) {
PyObject *dict = *dictptr;
if (dict == NULL && value != NULL) {
dict = PyDict_New();
if (dict == NULL)
goto done;
2001-08-02 01:15:00 -03:00
*dictptr = dict;
}
if (dict != NULL) {
if (value == NULL)
res = PyDict_DelItem(dict, name);
else
res = PyDict_SetItem(dict, name, value);
if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
PyErr_SetObject(PyExc_AttributeError, name);
goto done;
2001-08-02 01:15:00 -03:00
}
}
if (f != NULL) {
res = f(descr, obj, value);
goto done;
}
2001-08-02 01:15:00 -03:00
if (descr == NULL) {
PyErr_Format(PyExc_AttributeError,
"'%.50s' object has no attribute '%.400s'",
tp->tp_name, PyString_AS_STRING(name));
goto done;
2001-08-02 01:15:00 -03:00
}
PyErr_Format(PyExc_AttributeError,
"'%.50s' object attribute '%.400s' is read-only",
tp->tp_name, PyString_AS_STRING(name));
done:
Py_DECREF(name);
return res;
}
/* Test a value used as condition, e.g., in a for or if statement.
Return -1 if an error occurred */
int
2000-07-09 12:48:49 -03:00
PyObject_IsTrue(PyObject *v)
{
2006-02-15 13:27:45 -04:00
Py_ssize_t res;
if (v == Py_True)
return 1;
if (v == Py_False)
return 0;
1997-05-02 00:12:38 -03:00
if (v == Py_None)
return 0;
else if (v->ob_type->tp_as_number != NULL &&
v->ob_type->tp_as_number->nb_nonzero != NULL)
res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
else if (v->ob_type->tp_as_mapping != NULL &&
v->ob_type->tp_as_mapping->mp_length != NULL)
res = (*v->ob_type->tp_as_mapping->mp_length)(v);
else if (v->ob_type->tp_as_sequence != NULL &&
v->ob_type->tp_as_sequence->sq_length != NULL)
res = (*v->ob_type->tp_as_sequence->sq_length)(v);
else
return 1;
2006-02-15 13:27:45 -04:00
/* if it is negative, it should be either -1 or -2 */
return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
1990-12-20 11:06:42 -04:00
}
/* equivalent of 'not v'
1998-04-09 14:53:59 -03:00
Return -1 if an error occurred */
int
2000-07-09 12:48:49 -03:00
PyObject_Not(PyObject *v)
1998-04-09 14:53:59 -03:00
{
int res;
res = PyObject_IsTrue(v);
if (res < 0)
return res;
return res == 0;
}
/* Coerce two numeric types to the "larger" one.
Increment the reference count on each argument.
Return value:
-1 if an error occurred;
0 if the coercion succeeded (and then the reference counts are increased);
1 if no coercion is possible (and no error is raised).
*/
int
2000-07-09 12:48:49 -03:00
PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
{
1997-05-02 00:12:38 -03:00
register PyObject *v = *pv;
register PyObject *w = *pw;
int res;
if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
if (res <= 0)
return res;
}
if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
if (res <= 0)
return res;
}
return 1;
}
/* Coerce two numeric types to the "larger" one.
Increment the reference count on each argument.
Return -1 and raise an exception if no coercion is possible
(and then no reference count is incremented).
*/
int
2000-07-09 12:48:49 -03:00
PyNumber_Coerce(PyObject **pv, PyObject **pw)
{
int err = PyNumber_CoerceEx(pv, pw);
if (err <= 0)
return err;
1997-05-02 00:12:38 -03:00
PyErr_SetString(PyExc_TypeError, "number coercion failed");
return -1;
}
1990-10-14 09:07:46 -03:00
1995-01-25 20:38:22 -04:00
/* Test whether an object can be called */
int
2000-07-09 12:48:49 -03:00
PyCallable_Check(PyObject *x)
1995-01-25 20:38:22 -04:00
{
if (x == NULL)
return 0;
1997-05-02 00:12:38 -03:00
if (PyInstance_Check(x)) {
PyObject *call = PyObject_GetAttrString(x, "__call__");
1995-01-25 20:38:22 -04:00
if (call == NULL) {
1997-05-02 00:12:38 -03:00
PyErr_Clear();
1995-01-25 20:38:22 -04:00
return 0;
}
/* Could test recursively but don't, for fear of endless
recursion if some joker sets self.__call__ = self */
1997-05-02 00:12:38 -03:00
Py_DECREF(call);
1995-01-25 20:38:22 -04:00
return 1;
}
2001-08-02 01:15:00 -03:00
else {
return x->ob_type->tp_call != NULL;
}
1995-01-25 20:38:22 -04:00
}
/* Helper for PyObject_Dir.
Merge the __dict__ of aclass into dict, and recursively also all
the __dict__s of aclass's base classes. The order of merging isn't
defined, as it's expected that only the final set of dict keys is
interesting.
Return 0 on success, -1 on error.
*/
static int
merge_class_dict(PyObject* dict, PyObject* aclass)
{
PyObject *classdict;
PyObject *bases;
assert(PyDict_Check(dict));
assert(aclass);
/* Merge in the type's dict (if any). */
classdict = PyObject_GetAttrString(aclass, "__dict__");
if (classdict == NULL)
PyErr_Clear();
else {
int status = PyDict_Update(dict, classdict);
Py_DECREF(classdict);
if (status < 0)
return -1;
}
/* Recursively merge in the base types' (if any) dicts. */
bases = PyObject_GetAttrString(aclass, "__bases__");
if (bases == NULL)
PyErr_Clear();
else {
/* We have no guarantee that bases is a real tuple */
2006-02-15 13:27:45 -04:00
Py_ssize_t i, n;
n = PySequence_Size(bases); /* This better be right */
if (n < 0)
PyErr_Clear();
else {
for (i = 0; i < n; i++) {
int status;
PyObject *base = PySequence_GetItem(bases, i);
if (base == NULL) {
Py_DECREF(bases);
return -1;
}
status = merge_class_dict(dict, base);
Py_DECREF(base);
if (status < 0) {
Py_DECREF(bases);
return -1;
}
}
}
Py_DECREF(bases);
}
return 0;
}
/* Helper for PyObject_Dir.
If obj has an attr named attrname that's a list, merge its string
elements into keys of dict.
Return 0 on success, -1 on error. Errors due to not finding the attr,
or the attr not being a list, are suppressed.
*/
static int
merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
{
PyObject *list;
int result = 0;
assert(PyDict_Check(dict));
assert(obj);
assert(attrname);
list = PyObject_GetAttrString(obj, attrname);
if (list == NULL)
PyErr_Clear();
else if (PyList_Check(list)) {
int i;
for (i = 0; i < PyList_GET_SIZE(list); ++i) {
PyObject *item = PyList_GET_ITEM(list, i);
if (PyString_Check(item)) {
result = PyDict_SetItem(dict, item, Py_None);
if (result < 0)
break;
}
}
}
Py_XDECREF(list);
return result;
}
/* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
docstring, which should be kept in synch with this implementation. */
PyObject *
PyObject_Dir(PyObject *arg)
{
/* Set exactly one of these non-NULL before the end. */
PyObject *result = NULL; /* result list */
PyObject *masterdict = NULL; /* result is masterdict.keys() */
/* If NULL arg, return the locals. */
if (arg == NULL) {
PyObject *locals = PyEval_GetLocals();
if (locals == NULL)
goto error;
result = PyMapping_Keys(locals);
if (result == NULL)
goto error;
}
/* Elif this is some form of module, we only want its dict. */
else if (PyModule_Check(arg)) {
masterdict = PyObject_GetAttrString(arg, "__dict__");
if (masterdict == NULL)
goto error;
if (!PyDict_Check(masterdict)) {
PyErr_SetString(PyExc_TypeError,
"module.__dict__ is not a dictionary");
goto error;
}
}
/* Elif some form of type or class, grab its dict and its bases.
We deliberately don't suck up its __class__, as methods belonging
to the metaclass would probably be more confusing than helpful. */
else if (PyType_Check(arg) || PyClass_Check(arg)) {
masterdict = PyDict_New();
if (masterdict == NULL)
goto error;
if (merge_class_dict(masterdict, arg) < 0)
goto error;
}
/* Else look at its dict, and the attrs reachable from its class. */
else {
PyObject *itsclass;
/* Create a dict to start with. CAUTION: Not everything
responding to __dict__ returns a dict! */
masterdict = PyObject_GetAttrString(arg, "__dict__");
if (masterdict == NULL) {
PyErr_Clear();
masterdict = PyDict_New();
}
else if (!PyDict_Check(masterdict)) {
Py_DECREF(masterdict);
masterdict = PyDict_New();
}
else {
/* The object may have returned a reference to its
dict, so copy it to avoid mutating it. */
PyObject *temp = PyDict_Copy(masterdict);
Py_DECREF(masterdict);
masterdict = temp;
}
if (masterdict == NULL)
goto error;
/* Merge in __members__ and __methods__ (if any).
XXX Would like this to go away someday; for now, it's
XXX needed to get at im_self etc of method objects. */
if (merge_list_attr(masterdict, arg, "__members__") < 0)
goto error;
if (merge_list_attr(masterdict, arg, "__methods__") < 0)
goto error;
/* Merge in attrs reachable from its class.
CAUTION: Not all objects have a __class__ attr. */
itsclass = PyObject_GetAttrString(arg, "__class__");
if (itsclass == NULL)
PyErr_Clear();
else {
int status = merge_class_dict(masterdict, itsclass);
Py_DECREF(itsclass);
if (status < 0)
goto error;
}
}
assert((result == NULL) ^ (masterdict == NULL));
if (masterdict != NULL) {
/* The result comes from its keys. */
assert(result == NULL);
result = PyDict_Keys(masterdict);
if (result == NULL)
goto error;
}
assert(result);
if (!PyList_Check(result)) {
PyErr_SetString(PyExc_TypeError,
"Expected keys() to be a list.");
goto error;
}
if (PyList_Sort(result) != 0)
goto error;
else
goto normal_return;
error:
Py_XDECREF(result);
result = NULL;
/* fall through */
normal_return:
Py_XDECREF(masterdict);
return result;
}
1995-01-25 20:38:22 -04:00
1990-10-14 09:07:46 -03:00
/*
NoObject is usable as a non-NULL undefined value, used by the macro None.
There is (and should be!) no way to create other objects of this type,
1990-12-20 11:06:42 -04:00
so there is exactly one (which is indestructible, by the way).
(XXX This type and the type of NotImplemented below should be unified.)
1990-10-14 09:07:46 -03:00
*/
1992-03-27 13:26:13 -04:00
/* ARGSUSED */
1997-05-02 00:12:38 -03:00
static PyObject *
2000-07-09 12:48:49 -03:00
none_repr(PyObject *op)
1990-12-20 11:06:42 -04:00
{
1997-05-02 00:12:38 -03:00
return PyString_FromString("None");
1990-10-14 09:07:46 -03:00
}
/* ARGUSED */
static void
none_dealloc(PyObject* ignore)
{
/* This should never get called, but we also don't want to SEGV if
* we accidently decref None out of existance.
*/
2002-08-07 13:21:51 -03:00
Py_FatalError("deallocating None");
}
static PyTypeObject PyNone_Type = {
1997-05-02 00:12:38 -03:00
PyObject_HEAD_INIT(&PyType_Type)
1990-10-14 09:07:46 -03:00
0,
"NoneType",
1990-10-14 09:07:46 -03:00
0,
0,
none_dealloc, /*tp_dealloc*/ /*never called*/
0, /*tp_print*/
1990-12-20 11:06:42 -04:00
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
none_repr, /*tp_repr*/
1990-12-20 11:06:42 -04:00
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
1990-10-14 09:07:46 -03:00
};
1997-05-02 00:12:38 -03:00
PyObject _Py_NoneStruct = {
PyObject_HEAD_INIT(&PyNone_Type)
1990-10-14 09:07:46 -03:00
};
/* NotImplemented is an object that can be used to signal that an
operation is not implemented for the given type combination. */
static PyObject *
NotImplemented_repr(PyObject *op)
{
return PyString_FromString("NotImplemented");
}
static PyTypeObject PyNotImplemented_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0,
"NotImplementedType",
0,
0,
none_dealloc, /*tp_dealloc*/ /*never called*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
NotImplemented_repr, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
};
PyObject _Py_NotImplementedStruct = {
PyObject_HEAD_INIT(&PyNotImplemented_Type)
};
void
_Py_ReadyTypes(void)
{
if (PyType_Ready(&PyType_Type) < 0)
Py_FatalError("Can't initialize 'type'");
if (PyType_Ready(&_PyWeakref_RefType) < 0)
Py_FatalError("Can't initialize 'weakref'");
if (PyType_Ready(&PyBool_Type) < 0)
Py_FatalError("Can't initialize 'bool'");
if (PyType_Ready(&PyBytes_Type) < 0)
Py_FatalError("Can't initialize 'bytes'");
if (PyType_Ready(&PyString_Type) < 0)
Py_FatalError("Can't initialize 'str'");
if (PyType_Ready(&PyList_Type) < 0)
Py_FatalError("Can't initialize 'list'");
if (PyType_Ready(&PyNone_Type) < 0)
Py_FatalError("Can't initialize type(None)");
if (PyType_Ready(&PyNotImplemented_Type) < 0)
Py_FatalError("Can't initialize type(NotImplemented)");
}
1990-10-14 09:07:46 -03:00
#ifdef Py_TRACE_REFS
1990-10-14 09:07:46 -03:00
void
2000-07-09 12:48:49 -03:00
_Py_NewReference(PyObject *op)
1990-10-14 09:07:46 -03:00
{
_Py_INC_REFTOTAL;
1990-10-14 09:07:46 -03:00
op->ob_refcnt = 1;
_Py_AddToAllObjects(op, 1);
_Py_INC_TPALLOCS(op);
1990-10-14 09:07:46 -03:00
}
void
2000-07-09 12:48:49 -03:00
_Py_ForgetReference(register PyObject *op)
1990-10-14 09:07:46 -03:00
{
#ifdef SLOW_UNREF_CHECK
register PyObject *p;
#endif
if (op->ob_refcnt < 0)
1997-05-02 00:12:38 -03:00
Py_FatalError("UNREF negative refcnt");
if (op == &refchain ||
op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
1997-05-02 00:12:38 -03:00
Py_FatalError("UNREF invalid object");
#ifdef SLOW_UNREF_CHECK
1990-12-20 11:06:42 -04:00
for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
if (p == op)
break;
}
if (p == &refchain) /* Not found */
1997-05-02 00:12:38 -03:00
Py_FatalError("UNREF unknown object");
#endif
1990-10-14 09:07:46 -03:00
op->_ob_next->_ob_prev = op->_ob_prev;
op->_ob_prev->_ob_next = op->_ob_next;
op->_ob_next = op->_ob_prev = NULL;
_Py_INC_TPFREES(op);
1990-12-20 11:06:42 -04:00
}
void
2000-07-09 12:48:49 -03:00
_Py_Dealloc(PyObject *op)
1990-12-20 11:06:42 -04:00
{
destructor dealloc = op->ob_type->tp_dealloc;
1997-05-02 00:12:38 -03:00
_Py_ForgetReference(op);
(*dealloc)(op);
1990-10-14 09:07:46 -03:00
}
/* Print all live objects. Because PyObject_Print is called, the
* interpreter must be in a healthy state.
*/
void
2000-07-09 12:48:49 -03:00
_Py_PrintReferences(FILE *fp)
1990-10-14 09:07:46 -03:00
{
1997-05-02 00:12:38 -03:00
PyObject *op;
fprintf(fp, "Remaining objects:\n");
1990-10-14 09:07:46 -03:00
for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1997-05-02 00:12:38 -03:00
if (PyObject_Print(op, fp, 0) != 0)
PyErr_Clear();
1990-10-14 09:07:46 -03:00
putc('\n', fp);
}
}
/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
* doesn't make any calls to the Python C API, so is always safe to call.
*/
void
_Py_PrintReferenceAddresses(FILE *fp)
{
PyObject *op;
fprintf(fp, "Remaining object addresses:\n");
for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
op->ob_refcnt, op->ob_type->tp_name);
}
PyObject *
2000-07-09 12:48:49 -03:00
_Py_GetObjects(PyObject *self, PyObject *args)
{
int i, n;
PyObject *t = NULL;
PyObject *res, *op;
if (!PyArg_ParseTuple(args, "i|O", &n, &t))
return NULL;
op = refchain._ob_next;
res = PyList_New(0);
if (res == NULL)
return NULL;
for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
while (op == self || op == args || op == res || op == t ||
(t != NULL && op->ob_type != (PyTypeObject *) t)) {
op = op->_ob_next;
if (op == &refchain)
return res;
}
if (PyList_Append(res, op) < 0) {
Py_DECREF(res);
return NULL;
}
op = op->_ob_next;
}
return res;
}
1990-10-14 09:07:46 -03:00
#endif
1996-01-11 21:24:09 -04:00
/* Hack to force loading of cobject.o */
1996-12-05 17:58:58 -04:00
PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
/* Hack to force loading of abstract.o */
2006-02-15 13:27:45 -04:00
Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
2000-08-16 09:27:23 -03:00
/* Python's malloc wrappers (see pymem.h) */
void *
2000-07-09 12:48:49 -03:00
PyMem_Malloc(size_t nbytes)
{
return PyMem_MALLOC(nbytes);
}
void *
PyMem_Realloc(void *p, size_t nbytes)
{
return PyMem_REALLOC(p, nbytes);
}
void
PyMem_Free(void *p)
{
PyMem_FREE(p);
}
/* These methods are used to control infinite recursion in repr, str, print,
etc. Container objects that may recursively contain themselves,
e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
Py_ReprLeave() to avoid infinite recursion.
Py_ReprEnter() returns 0 the first time it is called for a particular
object and 1 every time thereafter. It returns -1 if an exception
occurred. Py_ReprLeave() has no return value.
See dictobject.c and listobject.c for examples of use.
*/
#define KEY "Py_Repr"
int
2000-07-09 12:48:49 -03:00
Py_ReprEnter(PyObject *obj)
{
PyObject *dict;
PyObject *list;
2006-02-15 13:27:45 -04:00
Py_ssize_t i;
dict = PyThreadState_GetDict();
if (dict == NULL)
return 0;
list = PyDict_GetItemString(dict, KEY);
if (list == NULL) {
list = PyList_New(0);
if (list == NULL)
return -1;
if (PyDict_SetItemString(dict, KEY, list) < 0)
return -1;
Py_DECREF(list);
}
i = PyList_GET_SIZE(list);
while (--i >= 0) {
if (PyList_GET_ITEM(list, i) == obj)
return 1;
}
PyList_Append(list, obj);
return 0;
}
void
2000-07-09 12:48:49 -03:00
Py_ReprLeave(PyObject *obj)
{
PyObject *dict;
PyObject *list;
2006-02-15 13:27:45 -04:00
Py_ssize_t i;
dict = PyThreadState_GetDict();
if (dict == NULL)
return;
list = PyDict_GetItemString(dict, KEY);
if (list == NULL || !PyList_Check(list))
return;
i = PyList_GET_SIZE(list);
/* Count backwards because we always expect obj to be list[-1] */
while (--i >= 0) {
if (PyList_GET_ITEM(list, i) == obj) {
PyList_SetSlice(list, i, i + 1, NULL);
break;
}
}
}
/* Trashcan support. */
/* Current call-stack depth of tp_dealloc calls. */
int _PyTrash_delete_nesting = 0;
/* List of objects that still need to be cleaned up, singly linked via their
* gc headers' gc_prev pointers.
*/
PyObject *_PyTrash_delete_later = NULL;
/* Add op to the _PyTrash_delete_later list. Called when the current
* call-stack depth gets large. op must be a currently untracked gc'ed
* object, with refcount 0. Py_DECREF must already have been called on it.
*/
void
2000-07-09 12:48:49 -03:00
_PyTrash_deposit_object(PyObject *op)
{
assert(PyObject_IS_GC(op));
assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
assert(op->ob_refcnt == 0);
_Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
_PyTrash_delete_later = op;
}
/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
* the call-stack unwinds again.
*/
void
2000-07-09 12:48:49 -03:00
_PyTrash_destroy_chain(void)
{
while (_PyTrash_delete_later) {
PyObject *op = _PyTrash_delete_later;
destructor dealloc = op->ob_type->tp_dealloc;
_PyTrash_delete_later =
(PyObject*) _Py_AS_GC(op)->gc.gc_prev;
/* Call the deallocator directly. This used to try to
* fool Py_DECREF into calling it indirectly, but
* Py_DECREF was already called on this object, and in
* assorted non-release builds calling Py_DECREF again ends
* up distorting allocation statistics.
*/
assert(op->ob_refcnt == 0);
++_PyTrash_delete_nesting;
(*dealloc)(op);
--_PyTrash_delete_nesting;
}
}
#ifdef __cplusplus
}
#endif